簡體   English   中英

真正的同步ajax調用

[英]Real synchronous ajax call

我有一種情況,我不知道我是否能正確靠近,但事情就這樣了:我希望第二次POST發生,但前提是第一個POST表示OK。

function save_match(slot, save) {
    listItems.each(function(idx, li) {
        var player = $(li);
        if(i >= 0) {
            // do some work
        } else {
            // post that should prevent second post from executing, depending on `return_msg`
            $.post(..., function(return_msg) {
                    if(return_msg == "not_ok") {
                        // I did this in hope that it will do the trick, but no
                        location.reload();
                    }
                }
            );
        }
    });

    // do a little work

    $.ajax({
        ...
    });
}

我試圖放置一個繁忙的循環,但這會凍結瀏覽器。 我想使第一個POST調用同步化(但是//do some work不允許//do some work ,直到POST返回為止,在93%的情況下,它返回ok ,但是我看不到其他選擇,如果可以的話,請讓我知道),這樣,如果第一個呼叫返回失敗,則不會發生第二個POST。

因此,我發現了一個問題: 如何使一個jQuery“ $。post”請求同步 ,這表明它的最佳答案已被棄用,並給出了會阻止UI的內容。 但是,我想阻止代碼執行第二個調用!

2015年該如何做?

一種方法是使ajax同步,這是不推薦的。 您可以在ajax調用中設置async: false

另一種方法是將一個ajax請求放入另一個的成功回調中。 一個簡單的例子是:

$.ajax({
    url: "ajaxUrl",
    type: "post",
    success: function (data) {
        if (data == "OK") {
            //do other ajax
        }
        else {

        }
    },
    error: function (jqxhr) { }
});

對於您的情況,上面的示例可能就足夠了。 對於更健壯和可擴展的解決方案,可以使用jQuery.Deferred 一個適合您情況的簡單示例:

var def = $.Deferred(); //Create $.Deferred;

$.ajax({
    url: "ajaxUrl",
    type: "post",
    success: function (data) {
        if (data == "OK")
            def.resolve(); //Let deferred know it was resolved with success
        else
            def.reject(); //Let deferred know it ended in a failure
    },
    error: function (jqxhr) { }
});

def.done(function () {
    //this will only run when deferred is resolved
}).fail(function(){
    //this will only run when deferred is rejected
}).always(function(){
    //this will run when deferred is either resolved or rejected
})

您正在警告“錯誤!” return_msg不等於not_ok 如果該消息是ok還是not_ok ,那是您要發表第二條帖子的地方,看來您已經知道如何發表。

    $.post(..., function(return_msg) {
            // check for the success, as null or something else would be an error too
            if(return_msg == "ok") { 
                // This is where you would do another post
                $.post(..., function() {});
            } else {
                // This is where the error should be.
            }
        }
    );

暫無
暫無

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

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