[英]Making an ajax request multiple times
I have three "sources," each of which needs to have an ajax call made. 我有三个“源”,每个源都需要进行ajax调用。 However, because Ajax is asynchronous, I can't just put it in a for loop.
但是,由于Ajax是异步的,所以我不能仅仅将其放入for循环中。 At the same time, I can't do
async: false
because it's bad to have the browser hang. 同时,我无法执行
async: false
因为挂起浏览器很不好。
Thus, I decided to have the Ajax be called multiple times in it's success
callback, and construct a kind of artificial loop. 因此,我决定在其
success
回调中多次调用Ajax,并构造一种人工循环。 Problem is, it's not working properly (I'll explain the error later on in the question). 问题是,它无法正常工作(我将在稍后的问题中解释错误)。 Here's my relevant code.
这是我的相关代码。
counter: 0,
load: function(source, start_month, end_month, start_year, end_year) {
start_month = parseInt(start_month) + 1;
end_month = parseInt(end_month) + 1;
var parseDate = d3.time.format("%Y-%m-%d").parse;
if(source == 0) {
$.ajax({
dataType: "json",
url: ...
data: {
...
},
crossDomain: true,
success: function(raw_data) {
posts.counter++;
if(posts.counter < 4) {
alert(posts.counter);
posts.load(source, start_month, end_month, start_year, end_year);
} else {
alert("plot graph");
}
}
});
}
...
This entire code block exists inside a posts
closure. 整个代码块都在
posts
闭包内部。 Just a couple of questions: 只是几个问题:
Is this good style? 这是好风格吗? Is there a more efficient way to go about doing this?
有没有更有效的方法可以做到这一点?
For some reason the alert
is only firing twice... shouldn't it be firing 3 times with 1, 2, and 3? 出于某种原因,
alert
仅触发两次……难道不是要用1、2和3触发3次吗?
I suggest using JS promises (aka deferred objects). 我建议使用JS Promise(也称为延迟对象)。 Look into jQuery's when and then functions ( http://api.jquery.com/jquery.when/ and http://api.jquery.com/deferred.then/ ).
查看jQuery的时间和功能( http://api.jquery.com/jquery.when/和http://api.jquery.com/deferred.then/ )。 You can use deferred objects to make 3 asynchronous calls and wait to process the data until all 3 calls return.
您可以使用延迟的对象进行3次异步调用,然后等待处理数据,直到所有3个调用都返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.