[英]Making an ajax request multiple times
我有三个“源”,每个源都需要进行ajax调用。 但是,由于Ajax是异步的,所以我不能仅仅将其放入for循环中。 同时,我无法执行async: false
因为挂起浏览器很不好。
因此,我决定在其success
回调中多次调用Ajax,并构造一种人工循环。 问题是,它无法正常工作(我将在稍后的问题中解释错误)。 这是我的相关代码。
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");
}
}
});
}
...
整个代码块都在posts
闭包内部。 只是几个问题:
这是好风格吗? 有没有更有效的方法可以做到这一点?
出于某种原因, alert
仅触发两次……难道不是要用1、2和3触发3次吗?
我建议使用JS Promise(也称为延迟对象)。 查看jQuery的时间和功能( http://api.jquery.com/jquery.when/和http://api.jquery.com/deferred.then/ )。 您可以使用延迟的对象进行3次异步调用,然后等待处理数据,直到所有3个调用都返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.