簡體   English   中英

為什么此ajax發布請求在Nodejs express中執行發布請求之前立即使用數據執行GET請求?

[英]Why is this ajax post request executing a GET request with the data right before the post request is executed in Nodejs express?

我這里有一個有趣的問題。 這是我要使用ajax對服務器執行發布請求的表單。

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發布請求的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的發布請求正在正確執行,並且答復已添加到數據庫和所有內容中,但是,在執行發布請求時,頁面會不斷重新加載,因為此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 - -

(上面是控制台輸出,我的問題是為什么執行帶有我提交的數據的get請求?如何防止這種情況發生?)

謝謝您的幫助。

您似乎正在提交表單和ajax請求。 嘗試添加以下內容以防止執行默認的提交操作(GET)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM