簡體   English   中英

AJAX 循環結束后執行代碼

[英]execute code after AJAX loop finished

我有一個被稱為“i”的 AJAX 調用。 我只想在最后一個 AJAX processData 回調函數完成后執行其余的代碼(它將 .csv 的值填充到一個名為“lines”的數組中,並且在所有迭代完成后我需要完成的數組)。 到目前為止,它只能通過使用“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)

您可以使用JavaScript promise功能。

在承諾中提出AJAX請求。 創建一個包含所有這些promise的數組。

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); }); 

設置一個計數器並在調用函數之前檢查其值

$("#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);
    }
}

你可以做這樣的事情。

最后一次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);
}

要么

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
      }
    }

使用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);
}

我添加了一個函數作為參數。 加載完成后,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