真正的同步ajax调用

时间:2015-09-15 17:30:58

标签: javascript jquery ajax post synchronization

我有一种情况,我不知道我是否正确接近,但在这里:我想要发生第二次POST,但前提是第一次POST说好了。

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执行,直到POST返回,在93%它返回ok,但我不能看另一个选择,如果可以的话,请告诉我),这样如果第一个电话的回复不合适,第二个POST就不会发生。

所以,我发现了这个问题:how to make a jquery “$.post” request synchronous,它说它的最佳答案已被弃用,并提供了阻止用户界面的内容。但是,我想阻止代码执行第二次调用!

2015年如何做到这一点?

2 个答案:

答案 0 :(得分:1)

一种方法是使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
})

答案 1 :(得分:1)

你警告"错误!"当return_msg不等于not_ok时。如果邮件是oknot_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.
            }
        }
    );