如何从nodejs中获取ajax中的响应
我正在尝试提交表单,然后通过AJAX发送状态success
。 但是当我在提交表单后从NodeJS发送状态时,它没有到达AJAX代码,因为我已经发出了一个alert()
语句来检查它是否到达它。 警报未被触发,但它会直接打印我在send('this text is printed')
写入的值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数据。