如何从nodejs在ajax中进行响应 [英] how to take a response in ajax from nodejs
问题描述
我正在尝试提交表单,然后它通过AJAX发送状态success
.
但是,当我在提交表单后从NodeJS发送状态时,它没有到达AJAX代码,因为我已经放置了alert()
语句来检查它是否到达了它.警报不会触发,但会直接打印我在send('this text is printed')
中编写的值.
I am trying submit a form and after that it send a status success
via AJAX.
But when I'm sending a status from NodeJS after submitting the form it does not reach the AJAX code, as I have put an alert()
statement to check if it reaches it. The alert is not triggered, but it directly prints that value which I wrote in send('this text is printed')
.
我的test.js文件是
My test.js file is
$(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代码
and my NodeJS code is given below
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数据.
You have to change res.send() to res.json() in order to be able to send JSON data.
这篇关于如何从nodejs在ajax中进行响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!