【问题标题】:how to take a response in ajax from nodejs如何从nodejs获取ajax响应
【发布时间】:2018-01-27 19:38:12
【问题描述】:

我正在尝试提交一个表单,然后它通过 AJAX 发送一个状态 success。 但是,当我在提交表单后从 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'
            });
        }
    });
});

【问题讨论】:

  • there is no alert in ajax but directly print that send('') value - 你能澄清一下这是什么意思吗?我不明白是什么问题。
  • @Hamsterrific 表示我在我的 ajax 代码中指定 alert(result.status); 但它不会发生而不是 res.send({ 'this is printed in next page' }) ; 这个事件

标签: jquery node.js ajax


【解决方案1】:

您必须将 res.send() 更改为 res.json() 才能发送 JSON 数据。

【讨论】:

  • ajax 还是没有响应。
  • 这应该是评论
猜你喜欢
  • 1970-01-01
  • 2012-10-02
  • 2021-11-15
  • 2012-07-01
  • 2016-09-24
  • 1970-01-01
  • 2017-08-22
  • 2014-10-29
相关资源
最近更新 更多