开发者

How to signal when AJAX completes

I have two ajax $.get() requests that I need to synchronize.

Essentially

var signal1 = false;
var signal2 = false;

    $.get(url,
                {},
                function (data) { 
                    signal1 = true;//callback complete.
                },'json');

    $.get(url2,
                {},
                function (data) { 
                    signal2 = true;//callback complete.
                }开发者_Go百科,'json');

    when(signal1 && signal2 == true)
       $.get(url3...

How can I, should I accomplish this type of task? (Bonus, what's the AJAX signature for failure callback?)


Look at the jquery deferred/promise methods, they are for exactly what you are trying to do.

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
   // a1 and a2 are the results of your two calls.
});

http://api.jquery.com/jQuery.when/

http://api.jquery.com/deferred.promise/


You do it like this:

$.when(
    $.get(url, {}, function(data) { 
        // signal 1 complete
    }, 'json'),
    $.get(url2, {}, function(data) { 
        // signal 2 complete
    }, 'json')
).then(function() {
    // success after both methods finish
}, function() {
    // failure method
});

See jQuery.when: http://api.jquery.com/jQuery.when/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜