【问题标题】:Chaining AJAX handlers with jQuery Deferred使用 jQuery Deferred 链接 AJAX 处理程序
【发布时间】:2013-07-10 18:18:48
【问题描述】:

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

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

这是我的代码,a 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);
        }
    )
);

有时,但并非总是,“3”会在“1”和“2”之前发出警报。立即执行第三个 AJAX 调用没有问题,但它的 done 处理程序需要最后执行。

【问题讨论】:

    标签: javascript jquery jquery-deferred


    【解决方案1】:

    你可以的

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

    你错过了这一行的“function(){” $.when(firstAjax, secondAjax).done(function(){
    http://jsfiddle.net/ACBJs/1/

    【讨论】:

    • 另外,(a) 没有必要从 firstAjax 和 secondAjax 的 done 回调中 return jqXHR.promise();。与 .then() 回调不同,来自 .done() 回调的返回值/承诺没有下游影响。并且 (b) 你应该使用 console.log(...) 而不是 alert(...) 来测试这种东西,否则你可能(在某些情况下)将你自己的手指速度添加到事件链中。
    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多