【问题标题】:how to execute second loop iteration after ajax doneajax完成后如何执行第二次循环迭代
【发布时间】:2015-02-06 14:09:42
【问题描述】:

如何延迟 for 循环,直到函数“some_multi_ajax_function()”更改全局变量(exe_counter 将为 0)?

for (i = 0; i < some_data_list.length; i++) {
    exe_counter=1;
     if(i>0 && exe_counter != 0){
            delay{
                // delay for loop until some_multi_ajax_function() set exe_counter = 0
                // do not execute second iteration
            }
      }else{
            data = some_data_list[i];
           // Many ajax posts will be executed here. In the end exe_counter will be set to 0;
           some_multi_ajax_function(data);
      }
}

function some_multi_ajax_function(data){
    $.ajax({
            ...
      }.done(function(d) {
           // here it could be used another ajax function 
           exe_counter = 0;
      });
}

【问题讨论】:

  • 你的脚本到底应该做什么?
  • 按坐标搜索广告,协调从google api获取。并且可以搜索10次

标签: javascript ajax for-loop delay execution


【解决方案1】:

你用错误的解决方案来解决问题。

如果你想等待一个 Ajax 动作,你只能使用回调。

然后你应该递归地做:

function some_multi_ajax_function(data, i) {
    $.ajax({
        ...
    }.done(function(d) {
         if (i < data.length) {
             some_multi_ajax_function(data, i + 1);
         } else {
             // Do something in the end
         }
    });
}

some_multi_ajax_function(some_data_list, 0);

【讨论】:

  • 我做不到,因为 some_multi_ajax_function() 多次调用另一个 Ajax 函数
  • 所以只需通过添加此选项 async: false 使您的调用同步
猜你喜欢
  • 2020-07-02
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
相关资源
最近更新 更多