我想在一个click事件中调用三个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*/});
});
发布于 2011-11-20 16:08:55
看起来你已经对这个问题有了一些答案,但是我认为这里有一些值得一提的东西,它将极大地简化你的代码。jQuery在v1.5中引入了$.when
。看起来是这样的:
$.when($.ajax(...), $.ajax(...)).then(function (resp1, resp2) {
//this callback will be fired once all ajax calls have finished.
});
我没看到这里提到,希望它能帮上忙。
发布于 2010-12-07 02:07:09
我自己看不出有什么东西是有问题的。Simple有一个整型变量。当您发起请求时,请递增该数字。当一个完成时,递减它。当它为零时,没有正在进行的请求,所以你就完成了。
$('#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
}
});
});
发布于 2016-06-02 12:42:35
值得注意的是,由于$.when
希望所有的ajax请求都是顺序参数(而不是数组),因此您通常会看到$.when
与.apply()
一起使用,如下所示:
// Save all requests in an array of jqXHR objects
var requests = arrayOfThings.map(function(thing) {
return $.ajax({
method: 'GET',
url: 'thing/' + thing.id
});
});
$.when.apply(this, requests).then(function(resp1, resp2/*, ... */) {
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var responseArgsArray = Array.prototype.slice.call(this, arguments);
});
使用Spread syntax,您现在可以像这样编写以下代码:
$.when(...requests).then((...responses) => {
// do something with responses
})
这是因为$.when
接受如下所示的参数
$.when(ajaxRequest1, ajaxRequest2, ajaxRequest3);
不是这样的:
$.when([ajaxRequest1, ajaxRequest2, ajaxRequest3]);
https://stackoverflow.com/questions/4368946
复制相似问题