針對多個Ajax調用的jQuery回調我想在一個點擊事件中進行三個Ajax調用。每個Ajax調用都執行不同的操作,并返回最終回調所需的數據。調用本身并不依賴于彼此,它們可以同時進行,但是我希望在這三個調用完成后進行最后的回調。$('#button').click(function() {
fun1();
fun2();
fun3();//now do something else when the requests have done their 'success' callbacks.});var fun1= (function() {
$.ajax({/*code*/});});var fun2 = (function() {
$.ajax({/*code*/});});var fun3 = (function() {
$.ajax({/*code*/});});
3 回答
墨色風雨
TA貢獻1853條經驗 獲得超6個贊
通知
$.when($.ajax(), [...]).then(function(results){},[...]);[使用]
// 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);
};
};})();
繁華開滿天機
TA貢獻1816條經驗 獲得超4個贊
$('#button').click(function() {
var inProgress = 0;
function handleBefore() {
inProgress++;
};
function handleComplete() {
if (!--inProgress) {
// do what's in here when all requests have completed.
}
};
$.ajax({
beforeSend: handleBefore,
complete: function () {
// whatever
handleComplete();
// whatever
}
});
$.ajax({
beforeSend: handleBefore,
complete: function () {
// whatever
handleComplete();
// whatever
}
});
$.ajax({
beforeSend: handleBefore,
complete: function () {
// whatever
handleComplete();
// whatever
}
});});- 3 回答
- 0 關注
- 408 瀏覽
添加回答
舉報
0/150
提交
取消
