墨色风雨
下面是我编写的一个回调对象,您可以在其中设置一个回调,一旦全部完成,或者让每个回调都有自己的回调,并在所有回调完成后都启动它们:通知由于jQuery1.5+可以使用另一个答案中描述的延迟方法: $.when($.ajax(), [...]).then(function(results){},[...]);这里延迟的例子对于jQuery<1.5,以下内容可以工作,或者如果您需要在未知的时间启动Ajax调用,如下面两个按钮所示:点击两个按钮后启动[使用]为单株回调完成后:工作实例// initialize herevar requestCallback = new MyRequestsCompleted({
numRequest: 3,
singleCallback: function(){
alert( "I'm the callback");
}});//usage in request$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.requestComplete(true);
}});$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.requestComplete(true);
}});$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.requestComplete(true);
}});各有他们自己当全部完成时回调:工作实例//initialize var requestCallback = new MyRequestsCompleted({
numRequest: 3});//usage in request$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.addCallbackToQueue(true, function() {
alert('Im the first callback');
});
}});$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.addCallbackToQueue(true, function() {
alert('Im the second callback');
});
}});$.ajax({
url: '/echo/html/',
success: function(data) {
requestCallback.addCallbackToQueue(true, function() {
alert('Im the third callback');
});
}});[守则]var MyRequestsCompleted = (function() {
var numRequestToComplete, requestsCompleted, callBacks, singleCallBack;
return function(options) {
if (!options) options = {};
numRequestToComplete = options.numRequest || 0;
requestsCompleted = options.requestsCompleted || 0;
callBacks = [];
var fireCallbacks = function() {
alert("we're all complete");
for (var i = 0; i < callBacks.length; i++) callBacks[i]();
};
if (options.singleCallback) callBacks.push(options.singleCallback);
this.addCallbackToQueue = function(isComplete, callback) {
if (isComplete) requestsCompleted++;
if (callback) callBacks.push(callback);
if (requestsCompleted == numRequestToComplete) fireCallbacks();
};
this.requestComplete = function(isComplete) {
if (isComplete) requestsCompleted++;
if (requestsCompleted == numRequestToComplete) fireCallbacks();
};
this.setCallback = function(callback) {
callBacks.push(callBack);
};
};})();