多个Ajax请求(带一个回调)
我正在发送多个ajax请求,并希望在所有请求都成功的情况下获得回调。 我找到了$.when($.ajax(), [...]).then(function(results){},[...]);
但这只有在事先知道你要做多少时才有效。 在我的情况下,它取决于用户输入。
我尝试了以下但我不确定$.when
适合的位置或方式:
$.when( $('#piecesTable tr').not(':first').each(function(){ // ...some prep... $.ajax({ // ...args here... }); }) ).then(function() { // All requests are done });
如何使用$.ajax
使用所有这些单独的$.ajax
调用的结果? 或者我以其他方式处理这个问题?
我认为你正在寻找的一般结构是这样的:
var requests = []; // Populate requests array with ajax requests. requests.push($.ajax({ // ... })); // Add as many requests as you want to the array. $.when.apply($, requests).done(function() { var args = $.prototype.slice.call(arguments); // args should contain the results of your ajax requests. // Do whatever with the results. });
有一个$.when.apply($, arrayOfPromises)
野兽的现代替代品: Promise.all
:
Promise.all(arrayOfPromises).then(function(arrayOfResults) { // Use arrayOfResults });
Promise.all
需要一个Promise.all
数组,并返回一个promise,当所有的thenables都已解析时,它会以一系列结果解析。 jQuery的承诺很好,因为它需要的只是它们才是可靠的。
您可以在任何具有Promise
支持的浏览器上使用此function,或者如果您包含Promise
填充/填充。
所以在你的情况下,你要构建数组:
var arrayOfPromises = []; $('#piecesTable tr').not(':first').each(function(){ // ...some prep... arrayOfPromises.push($.ajax({ // ** Push this promise into the array // ...args here... })); });
(或者您可以使用$.map
或Array#map
构建它。)
然后使用数组:
Promise.all(arrayOfPromises).then(function(arrayOfResults) { // Use arrayOfResults });
从jQuery文档:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).then( myFunc, myFailure );
两个ajax请求成功时执行myFunc
函数,如果任何一个有错误,则执行myFailure
。
所以你可以使用这个系统发送可变数量的请求,但仍然具有相同的回调函数:)
改编自@ TW80000答案:
var requests = []; .... $.when.apply($, requests ).done( myFunc, myFailure );