从循环中一次发送一个AJAX请求 [英] Sending one AJAX request at a time from a loop
问题描述
我知道这个问题已被无数次询问,但我无法弄清楚我的生活如何让这个答案在我的案例中起作用:等待异步javascript函数返回
I know this question has been asked countless times, but I cant figure out for the life of me how to make this answer work in my case: wait for async javascript function to return
我正在循环播放一些电视频道 在外环中,然后循环遍历内环中的一周中的日期。在内部循环中,我向服务器发出ajax请求以获取数据,然后我将其存储/缓存以供以后使用,如此
I'm looping through some "tv channels" in the outerloop and then looping through dates in the week in the innerloop. In the inner loop I make a ajax request to a server to fetch the data and I then store/cache it for later use like so
var dates = []; //<-- Contains a list of dates for the coming week
var baseUrl = "http://www.someserver.com";
var storedChannels = [1,2,3,4,5,6,7,8,9,10,45,23,56,34,23,67,23,567,234,67,345,465,67,34];
for(ch = 0; ch < storedChannels.length; ch++) {
var channel = storedChannels[ch];
for(d=0; d < 7; d++) {
var currentDate = dates[d];
ajax({
url: baseUrl+"?ch="+channel+"&dt=currentDate"+,
complete: function(res) {
CMLocalStore.setString('ch' + ch + "_" + scheduleDay, res);
},
});
//Want to wait here till the ajax request completes.
//Do not want to continue to next iteration.
//Do not want to fire of 50 bazillion ajax requests all at once
//Why? Very limited bandwidth scenario, plenty of channels
}
}
PS:没有请JQuery!简单的JS解决方案
PS: NO JQuery please! Plain JS solutions only
非常感谢!
推荐答案
你想要的东西像这样。我没有测试过,但希望你能得到这个想法。
You want something like this. I haven't tested it, but hopefully you should get the idea.
var dates = []; //<-- Contains a list of dates for the coming week
var baseUrl = "http://www.someserver.com";
var storedChannels = [1,2,3,4,5,6,7,8,9,10,45,23,56,34,23,67,23,567,234,67,345,465,67,34];
function ProcessNext(ch, d) {
if (d < 7) {
d++;
} else {
d=0;
if (ch < storedChannels.length) {
ch++;
} else {
return;
}
}
var channel = storedChannels[ch];
var currentDate = dates[d];
ajax({
url: baseUrl+"?ch="+channel+"&dt=currentDate"+,
complete: function(res) {
CMLocalStore.setString('ch' + ch + "_" + scheduleDay, res);
ProcessNext(ch, d);
},
});
}
ProcessNext(0, 0);
这篇关于从循环中一次发送一个AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!