Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/462.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 多次发出ajax请求_Javascript_Jquery_Ajax_Loops - Fatal编程技术网

Javascript 多次发出ajax请求

Javascript 多次发出ajax请求,javascript,jquery,ajax,loops,Javascript,Jquery,Ajax,Loops,我有三个“源”,每个源都需要进行ajax调用。然而,因为Ajax是异步的,所以我不能把它放在for循环中。同时,我不能执行async:false,因为挂起浏览器是不好的 因此,我决定在它的success回调中多次调用Ajax,并构造一种人工循环。问题是,它不能正常工作(稍后我将在问题中解释错误)。这是我的相关代码 counter: 0, load: function(source, start_month, end_month, start_year, end_year) {

我有三个“源”,每个源都需要进行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");
            }
          }
        });
      }
...
计数器:0,
加载:函数(源、开始月份、结束月份、开始年份、结束年份){
开始月份=parseInt(开始月份)+1;
月末=parseInt(月末)+1;
var parseDate=d3.time.format(“%Y-%m-%d”).parse;
如果(源==0){
$.ajax({
数据类型:“json”,
网址:。。。
数据:{
...
},
跨域:是的,
成功:函数(原始数据){
posts.counter++;
if(posts.counter<4){
警报(邮局、柜台);
加载(来源、开始月份、结束月份、开始年份、结束年份);
}否则{
警报(“绘图图”);
}
}
});
}
...
整个代码块存在于
posts
闭包中。只有几个问题:

  • 这种风格好吗?有没有更有效的方法

  • 出于某种原因,
    警报只触发了两次……不是吗
    用1、2和3发射3次


  • 我建议使用JS承诺(又名延迟对象)。您可以使用延迟对象进行3次异步调用,然后等待处理数据,直到所有3次调用都返回。

    1.这不一定是一种不好的方式。2.您确定其中一次请求期间没有出错吗?真不敢相信我没有检查。谢谢