简体   繁体   English

AJAX 循环结束后执行代码

[英]execute code after AJAX loop finished

I have an AJAX call that gets called "i" amount of times.我有一个被称为“i”的 AJAX 调用。 I want to execute the rest of the code only after the last AJAX processData callback function was finished (It fills values of the .csv into an array called "lines" and I need the finished array after all iterations have finished).我只想在最后一个 AJAX processData 回调函数完成后执行其余的代码(它将 .csv 的值填充到一个名为“lines”的数组中,并且在所有迭代完成后我需要完成的数组)。 So far it only works by using "setTimeout()" which is not a nice solution到目前为止,它只能通过使用“setTimeout()”来工作,这不是一个很好的解决方案

for (var i = 0; i < options.length; i++) {
    (function(index) {
        $.ajax({
            type: "GET",
            url: options[index] + ".csv",
            dataType: "text",
            success: function(data) {
                processData(data, options[index], type)
            }
        });
    })(i);
}
setTimeout(function() {
    getAveragePercentages(lines);
}, 500)

You can use the JavaScript promise functionality. 您可以使用JavaScript promise功能。

Make AJAX request in the promise. 在承诺中提出AJAX请求。 Create an array which will contains all these promise. 创建一个包含所有这些promise的数组。

Promise.all will be executed after all promise get resolved. Promise.all将在所有promise解决后执行。

 var promiseArr = []; for (var i = 0; i < options.length; i++) { var promise = new Promise(function(resolve, reject) { (function(index) { $.ajax({ type: "GET", url: options[index] + ".csv", dataType: "text", success: function(data) { processData(data, options[index], type); resolve('outputIfany') } }); })(i); }); promiseArr.push(promise); } Promise.all(promiseArr).then(function(values) { getAveragePercentages(lines); }); 

set up a counter and check it's value before calling your function 设置一个计数器并在调用函数之前检查其值

$("#counter").html("0");
for(var i=0;i<options.length;i++){
            (function(index){       
                $.ajax({ 
                    type: "GET",
                    url: options[index]+".csv",
                    dataType: "text",
                    success: function(data) {
                    processData(data, options[index], type)
                    var counter = $("#counter").html();
                    if( counter == options.length ){
                      getAveragePercentages(lines);
                    }
                     $("#counter").html(counter+1);
                   }
                });

            })(i);
        }
for (var i = 0; i < options.length; i++) {
    (function (index) {
        $.ajax({
            type: "GET",
            url: options[index] + ".csv",
            dataType: "text",
            success: function (data) {
                processData(data, options[index], type)
            }
        });
        counter = counter + 1;
    })(i);
    if (i == options.length) {
        getAveragePercentages(lines);
    }
}

You can do something like this. 你可以做这样的事情。

after last Loop Success call function 最后一次Loop Success调用函数之后

var totalRec = options.length;
for(var i=0;i<options.length;i++){
    (function(index){       
        $.ajax({ 
            type: "GET",
            url: options[index]+".csv",
            dataType: "text",
            success: function(data) {processData(data, options[index], type)


           if(i == (totalRec-1)){
              getAveragePercentages(lines);
           }
        }
        });
    })(i);
}

or 要么

var totalRec = options.length;
    for(var i=0;i<options.length;i++){
        (function(index){       
            $.ajax({ 
                type: "GET",
                url: options[index]+".csv",
                dataType: "text",
                success: function(data) {processData(data, options[index], type)


            }
            });
        })(i);

     if(i == (totalRec-1)){
          getAveragePercentages(lines); // gets called only when condition is true
      }
    }

It is not a good practice to use a setTimeOut for wait the ajax call, in my experience I've been using recursive functions for doing this, in your case you can do the following: 使用setTimeOut等待ajax调用不是一个好习惯,以我的经验,我一直在使用递归函数来执行此操作,在您的情况下,您可以执行以下操作:

var counter = 0;
function main()
{
    counter = 0;
    doAjaxCall(counter);
}

function doAjaxCall(counter)
{
    (function(index){       
                $.ajax({ 
                    type: "GET",
                    url: options[index]+".csv",
                    dataType: "text",
                    success: function(data) {
                       processData(data, options[index], type);
                       if(counter < options.length)
                       {
                           counter++;
                           doAjaxCall(counter); //We call the same function but with the next index
                       }
                       else
                       {
                          //The loop finished, countinue code after your for loop
                       }
                    }
                });
            })(i);
}

I added a function as a parameter.我添加了一个函数作为参数。 The AJAX calls the function when the load is completed.加载完成后,AJAX 调用该函数。

function loadDoc(call_back_func) {
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    json_data = JSON.parse(this.responseText);
    call_back_func();
  }
  xhttp.open("GET", "kanban_personal_template.json");
  xhttp.send();
}

function load_call_back()
{
    console.log(json_data);
}
loadDoc(load_call_back);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM