如何在AJAX完成时发出信号

时间:2011-09-26 18:40:19

标签: javascript jquery ajax signals

我有两个需要同步的ajax $.get()请求。

基本上

var signal1 = false;
var signal2 = false;

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

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

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

我该怎样才能完成这类任务? (Bonus,失败回调的AJAX签名是什么?)

2 个答案:

答案 0 :(得分:4)

查看jquery延迟/保证方法,它们完全符合您的要求。

$.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/

答案 1 :(得分:3)

你这样做:

$.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
});

请参阅jQuery.whenhttp://api.jquery.com/jQuery.when/