为什么这个ajax post请求在Nodejs express中执行post请求之前执行带有数据的GET请求?

时间:2015-09-15 02:00:03

标签: ajax node.js post express get

我这里有一个有趣的问题。这是我想使用ajax在服务器上执行post请求的表单。

replyPrefix = "<div id='addCommentContainer'><form class='addCommentForm' name='addcomment' id='addCommentForm'>" +
            "<div class='input-group'>" +
                "<input class='form-control' class='commentContent' type='text' placeholder='Comment!' name='commentContent'>" +
                "<input class='form-control' class='commentParent' type='hidden' name='parent' value='";
replySuffix = "'>" +
                "<span class='input-group-btn'>" +
                    "<button class='btn btn-danger' type='submit' class='submitButton'>submit</button>" +
                "</span>" +
            "</div></form></div>";

(回复的值插入在此表单的前缀/后缀之间。请注意,在我尝试转移到ajax之前,此表单和代码正在执行帖子请求)

这是我执行ajax post请求的jquery

$('.addCommentForm').submit(function() {

                $.ajax({
                    type: "POST",
                    url: "/addcomment",
                    data: $(this).serialize(),
                    success: function(data) {
                        console.log("success:");
                        //alert(data);
                    },
                    error: function(e) {
                        console.log("error:");
                    }
                });
            });

这是nodejs表示代码。

// handle add comment call
router.post('/addcomment', function(req, res) {

//var obj = {};
console.log('body: ' + JSON.stringify(req.body));
//res.send(req.body);

//return;

var db = req.db;
var collection = db.get('comments');

// grab parent id if available
var parent = req.body.parent;
var content = req.body.commentContent;

console.log("parent: " + parent);
console.log("content: " + content);

// if no parent available, add new bubble
if (!parent || parent == "") {
    console.log("Adding a bubble...");
    addBubble(db, collection, content);
}
// otherwise, add comment to tree
else {
    console.log("Adding a comment...");
    addComment(db, collection, content, parent);
}

// DEBUG
//console.log(parent);
//console.log(req.body.commentContent);

//res.redirect('/');
});

通过ajax的post请求正在正确执行,并且回复被添加到数据库和所有内容,但是当执行post请求时页面不断被重新加载,因为这个get请求每次都在它之前发送表格已提交。

body: {"commentContent":"asdf","parent":"55f778aab671e4b41d05c6a7"}
parent: 55f778aab671e4b41d05c6a7
content: asdf
Adding a comment...
GET /?commentContent=asdf&parent=55f778aab671e4b41d05c6a7 200 65.626 ms - 53620
POST /addcomment - - ms - -

(上面是控制台输出,我的问题是为什么这个获取请求与我提交的数据正在执行?我如何防止这种情况发生?)

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

看起来您正在提交表单和ajax请求。尝试添加以下内容以防止默认提交操作(GET)。

.submit(function(e) {
  e.preventDefault();
  //ajax code
}