繁体   English   中英

用jQuery Deferred链接AJAX处理程序

[英]Chaining AJAX handlers with jQuery Deferred

我只是似乎无法$.Deferred jQuery的$.Deferred调用的$.Deferred处理。

我要做的是执行三个AJAX调用,每个调用都对返回的数据执行一些处理。 第三个AJAX调用的成功调用要求完成前两个调用的处理,但是前两个调用的顺序无关紧要。

这是我的代码和一个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);
        }
    )
);

有时但并非总是如此,在“ 1”和“ 2”之前会提示“ 3”。 我立即执行第三个AJAX调用没有问题,但是它的完成处理程序需要最后执行。

你可以做

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

});    

您会错过$ .when(firstAjax,secondAjax).done(function(){
http://jsfiddle.net/ACBJs/1/

暂无
暂无

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

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