笑故挽风 2015-09-15 17:30 采纳率: 100%
浏览 22

真正的同步ajax调用

I have a situation, where I do not know if I am approaching correctly, but here it goes: I want a second POST to happen, but only if the first POST says 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({
        ...
    });
}

I tried to put a busy loop, but this will freeze the browser. I want to make the first POST call synchronous (which however won't let the //do some work execute, until the POST returns, which in 93% it returns ok, but I can't see another alternative, if you can, please let me know), so that the second POST won't happen if the return of the first call is not ok.

So, I found this question: how to make a jquery “$.post” request synchronous, which says that it's top answer is deprecated and gives something that will block UI. However, I want to block the code from executing the second call!

How to do this in year 2015?

  • 写回答

2条回答 默认 最新

  • weixin_33686714 2015-09-15 17:43
    关注

    One way is to make the ajax synchronous which is not recommended. You can set async: false on ajax call.

    Another way is to put one ajax request in the success callback of another. A simple example would be:

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

    For your situation, the example above would probably be enough. For a more robust and scalable solution you can use jQuery.Deferred. A simple example for your situation:

    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
    })
    
    评论

报告相同问题?