简体   繁体   English

执行ajax函数,直到成功执行另一个ajax调用

[英]Execute ajax function until get success of another ajax call

I need to execute an ajax function, the detail here is that i want to execute this function until another ajax function return success. 我需要执行一个ajax函数,这里的细节是我要执行这个函数,直到另一个ajax函数返回成功。

This is the function that will i have to wait to return success ( try..catch block) 这是我必须等待返回成功的函数( try..catch块)

Ajaxfunction1 Ajaxfunction1

$.ajax({
        type : "GET",
        url :url,
        data : parameters,
        success : function(msg) {
            try {
                var jsonObject = JSON.parse(msg);
                console.debug(msg);
                //SendToDMS(msg);
            } catch (e) {
                $("#SaveConfig").removeAttr("disabled");
                toastr.error(msg + '.', "Message");
            }
        },
        failure : function(msg) {
            $("#SaveConfig").removeAttr("disabled");
            toastr.error('Error: ' + msg + '.', "Message");
        }
    });

I want something like this: 我想要这样的东西:

while ( Ajaxfunction1 != success ) { // while the previous ajax function not return success execute this another ajax function
    $.ajax({
            type : "GET",
            url :url,
            data : parameters,
            success : function(msg) {
                // something on success
            },
            failure : function(msg) {
                // something when comes an error
            }
        });
}

How can I accomplish this? 我该怎么做? Thanks for your help 谢谢你的帮助

You can use the returned Deferred from $.ajax and check it's state() to see if it's resolved, rejected or pending, so something like this with a recursive function should do what you want. 您可以使用从$.ajax返回的Deferred并检查它的state()来查看它是否已解决,拒绝或挂起,因此具有递归功能的类似代码应该可以满足您的要求。

var waitFor = $.ajax({
    type : "GET",
    url  : url,
    data : parameters
}).done(function(msg) {
    try {
        var jsonObject = JSON.parse(msg);
    } catch (e) {
        $("#SaveConfig").removeAttr("disabled");
        toastr.error(msg + '.', "Message");
    }
}).fail(function(msg) {
    $("#SaveConfig").removeAttr("disabled");
    toastr.error('Error: ' + msg + '.', "Message");
});

(function rec() {
    $.ajax({
        type : "GET",
        url  : url,
        data : parameters
    }).always(function() {

        if (waitFor.state() != 'resolved') rec();

    }).done(function(msg) {
        // something on success
    }).fail(function(msg) {
        // something when comes an error
    });
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM