非阻塞解決方案,一樣快是通過成功回調異步而是順序給他們打電話:
定義你的方法以便它返回ajax對象。
function getHTTPStatusCode200(urlIn) {
return $.ajax({
url: urlIn
});
}
然後把它們連:
getHTTPStatusCode200(url1).complete(function(xhr1){
getHTTPStatusCode200(url2).complete(function(xhr2){
getHTTPStatusCode200(url3).complete(function(xhr3){
getHTTPStatusCode200(url4).complete(function(xhr4){
//all requests have been completed and you have access to all responses
}
}
}
}
這方面的工作作爲直接替代$。當:
$.when = function() {
this.requests = [];
this.completeFunc;
this.interval;
//if you want it to work jsut like $.when use this
this.requests = arguments;
//If you want to pass in URLs use this
//for(var i in arguments) {
// this.requests.push($.get(arguments[i]));
//};
this.complete = function(func) {
this.completeFunc = func;
var when = this;
this.interval = window.setInterval(function(){
checkReadyStates(when)
}, 100);
return this;
};
var checkReadyStates = function(when) {
var complete = 0;
for(var i in when.requests) {
if(when.requests[i].readyState==4) {
complete++;
}
}
if(complete == when.requests.length) {
window.clearInterval(when.interval);
when.completeFunc.apply(when, when.requests);
}
};
return this;
}
function handler(){
console.log('handler');
console.log(arguments);
//The arguments here are all of the completed ajax requests
//see http://api.jquery.com/jQuery.ajax/#jqXHR
}
$.when(xhr1,xhr2,xhr3).complete(handler);
//or
//$.when('index.php','index2.php','index3.php').complete(handler);
現在和工程測試。
如何在完整的處理程序內,看起來像是一個很好的地方堅持條件。 – adeneo
因爲你是jQuery的舊版本,如果你按順序運行它們,建議你在每個Ajax調用中使用'async:false'。請注意'async'會阻止你的瀏覽器,直到完成'ajax'爲止 – krishgopinath
這就是* when *的意思。爲什麼這不是一個選項?它在1.4沒有? –