我正在尝试提交表单,然后它会发送状态success
通过 AJAX。
但是,当我在提交表单后从 NodeJS 发送状态时,它不会到达 AJAX 代码,因为我已经放置了一个alert()
语句来检查它是否达到它。警报没有被触发,但它直接打印我写的值send('this text is printed')
.
我的 test.js 文件是
$(document).ready(function() {
$('#form_submit').click(function() {
$.ajax({
url: '/submitForm',
type: 'POST',
contentType: 'application/json',
success: function(result) {
alert(result.status);
if (result.status === "success") {
alert("success");
window.location = '/nextPage';
} else {
alert("failure");
}
},
error: function(err) {
alert('error');
}
})
});
});
我的 NodeJS 代码如下
app.post('/submitForm', function(req, res) {
// submitted form to database
var form = new Form({
name: req.body.name,
email: req.body.email,
number: req.body.number,
});
form.save(function(err) {
if (err) {
throw new Error(err);
} else {
res.send({
status: 'success',
message: 'successfully form created'
});
}
});
});
您必须将 res.send() 更改为 res.json() 才能发送 JSON 数据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)