真正的同步ajax调用

Real synchronous ajax call

本文关键字:ajax 调用 同步      更新时间:2023-09-26

我有一种情况,我不知道我是否接近正确,但这里是这样的:我想要第二个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执行,直到POST返回,其中93%返回ok,但我看不到另一个替代方案,如果可以,请让我知道),因此,如果第一个调用的返回不正确,第二个POST将不会发生。

所以,我发现了这个问题:如何使jquery"$。post"请求同步,这表示它的顶级答案已被弃用,并给出一些将阻塞UI的东西。但是,我想阻止代码执行第二个调用!

如何在2015年做到这一点?

一种方法是使ajax同步,这是不推荐的。

可以在ajax呼叫中设置async: false

另一种方法是将一个ajax请求放在另一个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时,您正在警告"错误!"如果消息是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.
            }
        }
    );