使用相同的 done 函数运行多个类似的 ajax 调用的正确方法,输入数据不同



所以我正在尝试对几乎相同的json向同一位置发出多个ajax请求,但是每次我都会发送不同的数据。

这是我到目前为止所拥有的,我将每个 ajax 请求添加到一个数组中,然后尝试在数组上运行 $.when,但没有任何反应。我发誓我以前见过这个,就像它是如何完成的。只是想知道像这样运行多个 ajax 调用的正确方法是什么。它们不相互依赖,但生成的 json纵,并对每个请求使用相同的方式。

这是我的代码:

var requests=[]
$('.element').not('.w').each(function(){
requests.push($.ajax({url:'https://api.url.com', data:{'q':$(this).children('.supportingText').text(), 'token':''}, dataType:'jsonp', method:'GET'}));
});
$.when(requests).done(function(response){
//check if element in response object is something and then add to array and edit the .element that is currently on.
}

与真正的承诺不同,jQuery的承诺略有不同。$.when在它的参数中不需要一系列承诺,它需要多个参数

使用Function#apply您可以使用数组来"填充"参数

同样,每个输入参数使用一个参数调用.done

您的代码可以重写:

$.when.apply($, requests).done(function(){
var response = [].slice.call(arguments);
// response is an array of responses
})

或 ES2016+ 传播运算符(如果您不这么认为,...实际上是代码的一部分)

$.when(...requests).done(function(...response){
// response is an array of responses
})

您可以使用Promise.all

Promise.all(requests).then((responses) => {
return responses.map((response) => {
// check if element in response object is something and then add to array and edit the .element that is currently on.
});
});

最新更新