我似乎无法处理jQuery对AJAX调用的$.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"one_answers"2"之前提醒"3"。我对立即执行第三个AJAX调用没有问题,但它的done处理程序需要最后执行。
您可以进行
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())这行的"function(){"http://jsfiddle.net/ACBJs/1/