我在带有id的某些项目上有一个foreach循环,在其中我有一个ajax调用。在成功函数中,我想将每个响应归因于其相应的ID。我怎样才能做到这一点?因为成功,我的身份证丢失了。我该怎么做:
for (i=0; i<items_to_print.length; i++) {
var item = items_to_print[i];
jQuery.ajax({
url: item.url,
dataType: "json",
data: item.data,
success: function(response, i) {
items_to_print[i]['response'] = response;
}
});
}
谢谢,
最佳答案
一种方法是减慢循环速度-仅在收到响应后转到数组中的下一项。
var items_to_print = [{url:"https...",data:{}},{url:"https...",data:{}},{url:"https...",data:{}}];
var count = 0;
makeCall();
function makeCall(){
if(count >= items_to_print.length){return;}
var _item = items_to_print[count];
jQuery.ajax({
url: item.url,
dataType: "json",
data: item.data,
success: _response
});
}
function _response(response){
items_to_print[count]['response'] = response;
count++;
makeCall();
}