在“使用Node.js和Express进行Web开发”一书中,有以下代码段:
app.post('/process', function(req, res){
if(req.xhr || req.accepts('json,html')==='json'){
// if there were an error, we would send { error: 'error description' }
res.send({ success: true });
}else{
// if there were an error, we would redirect to an error page
res.redirect(303, '/thank-you');
}
});
在else块中,我们可以执行以下操作:
console.log('Form (from querystring): ' + req.query.form);
console.log('CSRF token (fconsolerom hidden form field): ' + req.body._csrf);
console.log('Name (from visible form field): ' + req.body.name);
console.log('Email (from visible form field): ' + req.body.email);
我们会得到价值观。但是如果我们在if块中放入相同的块,则值都是'undefined'(因为它是ajax请求)。那么当它是ajax请求时我们如何读取请求参数呢?
编辑:我正在使用,表达和“Body Parser”
编辑:我用于制作ajax请求的jQuery代码:
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>