针对多个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 关注
- 411 浏览
添加回答
举报
0/150
提交
取消
