一个非阻塞的解决方案和同样快的是通过成功回调异步但按顺序调用它们:
定义您的方法,使其返回 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 的直接替代品:
$.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);
现在测试并且工作。