【问题标题】:AJAX post data almost saving to the db?AJAX 发布数据几乎保存到数据库?
【发布时间】:2014-06-22 08:04:25
【问题描述】:

测试模块,AJAX 正在浏览器的 console.log 中正确发布,并且 Node.js/express4 mongoose .save 方法正在正确保存到 MongoDB(使用 Postman - REST Client 进行测试)

由于某种原因,AJAX 发布数据尚未进入数据库,尽管它准确地记录了数据..

$(document).ready(function(){

    $('#SubmitBtn').click(function() {

        var message = $( "#message" ).val();

        console.log(message); // logs as the "user's message"

        var AjaxPostData = {'message' : message};

        console.log(AjaxPostData);  // logs as [object Object]

          // make an ajax call
          $.ajax({
            dataType: 'json',
            data: AjaxPostData,
            type: 'post',
                url:"http://localhost:4200/api/v1/stories",
                success: foundAllSuccess,
                error: foundAllFailure
            });

        console.log(AjaxPostData.message);  // logs as the "user's message"
    });
});

Express4 路由:

var router = express.Router();  // an instance of the express Router
var Story = require('./app/models/story');  // load the mongoose model

router.route('/stories')

    // create a story (accessed at POST http://localhost:4200/api/v1/stories)
    .post(function(req, res) {

        var story = new Story();  // create a new instance of the Story model
        story.message = req.body.message;  // set the message, from the request

        console.log(req.body.message); // logs with Postman, yet the ajax post

        // save the story, and check for errors
        story.save(function(err) {

            if (err)
                res.send(err);

            res.json({ message: 'Story "' + story.message + '" Created' });

        });
    })

app.use( '/api/v1', router );  // all of the routes are prefixed

【问题讨论】:

  • 您能否更具体地说明这里错误的性质?当您发布 AJAX 帖子时,您的 req.body.message 的 console.log 是否包含适当的内容?我还建议使用new Story({message: req.body.message}).save(callback),因为它更干净一些。最后,我将删除您对 AjaxPostData 的定义中的引号,因为据我所知,它们不是必需的。
  • @Michael req.body.message 的控制台日志没有记录 ajax 帖子。感谢建议的格式。将测试一切
  • @Michael 将格式修改为您更简洁的建议。控制台正在使用 POSTMAN 测试记录 req.body.message,而不是 ajax。也删除了引号,仍然没有保存 ajax 数据。任何其他建议?

标签: javascript jquery ajax node.js express


【解决方案1】:

原来ajax点击事件需要e.preventDefault();或者return false;

$('#SubmitBtn').click(function(e) {

    e.preventDefault();

    // do something
});

$('#SubmitBtn').click(function() {

    //do something

    return false;
});

在这种情况下都可以工作..虽然这里有一篇关于差异的精彩帖子:event.preventDefault() vs. return false

【讨论】:

    【解决方案2】:

    替换data: AjaxPostData,

    data : JSON.stringify(AjaxPostData), 我不相信数据被正确传递,这就是它在 [Object object] 发送的原因

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 2021-02-20
      • 2016-02-08
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多