简体   繁体   English

用jQuery Deferred链接AJAX处理程序

[英]Chaining AJAX handlers with jQuery Deferred

I just can't seem to get a handle on jQuery's $.Deferred handling of AJAX calls. 我只是似乎无法$.Deferred jQuery的$.Deferred调用的$.Deferred处理。

What I want to do is execute three AJAX calls, each of which performs some processing on the returned data. 我要做的是执行三个AJAX调用,每个调用都对返回的数据执行一些处理。 The success call of the third AJAX call requires that the processing from the first two calls be complete, but the order of the first two calls does not matter. 第三个AJAX调用的成功调用要求完成前两个调用的处理,但是前两个调用的顺序无关紧要。

Here is my code, and a jsFiddle : 这是我的代码和一个jsFiddle

var firstAjax = $.getJSON('/echo/json/')
.done(
    function(data, textStatus, jqXHR){
        //do some initialization here based on the data
        alert(1);
        return jqXHR.promise();
    }
);

var secondAjax = $.getJSON('/echo/json/')
.done(
    function(data, textStatus, jqXHR){
        //do some initialization here based on the data
        alert(2);
        return jqXHR.promise();
    }
);

$.when(firstAjax, secondAjax)
.done(
    $.getJSON('/echo/json/')
    .done(
        function(data, textStatus, jqXHR){
            //do some initialization here that relies on the initialization of the first and second calls being complete
            alert(3);
        }
    )
);

Sometimes, but not always, "3" is alerted before "1" and "2". 有时但并非总是如此,在“ 1”和“ 2”之前会提示“ 3”。 I have no problem with performing the third AJAX call immediately but its done handler needs to execute last. 我立即执行第三个AJAX调用没有问题,但是它的完成处理程序需要最后执行。

you can do 你可以做

var firstAjax = $.getJSON('/echo/json/').done(
function(data, textStatus, jqXHR){
    //do some initialization here based on the data
    alert(1);
    return jqXHR.promise();
}
);

var secondAjax = $.getJSON('/echo/json/')
.done(
function(data, textStatus, jqXHR){
    //do some initialization here based on the data
    alert(2);
    return jqXHR.promise();
}
);

$.when(firstAjax, secondAjax)
.done(function(){ 
 $.getJSON('/echo/json/')
.done(
    function(data, textStatus, jqXHR){
        //do some initialization here that relies on the initialization of the first and second calls being complete

  alert(3);
    }
)

});    

you miss the "function(){" on this line $.when(firstAjax, secondAjax).done(function(){ 您会错过$ .when(firstAjax,secondAjax).done(function(){
http://jsfiddle.net/ACBJs/1/ http://jsfiddle.net/ACBJs/1/

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

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