Async AjaxCall in a for loop Javascript

Async AjaxCall in a for loop Javascript

本文关键字:loop Javascript for AjaxCall in Async      更新时间:2023-09-26

如何使每次迭代都成为需要异步的新Ajax调用。不使用

async: false,

如果我使用异步执行此操作,我会收到一条警告消息,并且我的 UI 冻结,我该如何解决这个问题?这不是正常的 for 循环

编辑1

var username = "username1";
var password = "test";
var code = "";
for(var i = 0; i < results.lenght;i++){
   $.ajax({
        data: {username:username, password: password},
        url: './php/'+results[i].NAME+'.php',
        method: 'POST',
        datatype: 'json',
        success: function(msg) {
           //all the msg info needs to be filled in in the html. via the var "code"
        }
        });    
    }
return code;

使用 jQuery Ajax 请求的 promise 语义。

var params = {
    username: "username1",
    password: "test"
};
// build an array of Ajax requests
var requests = results.map(function (result) {
    var url = './php/' + encodeURIComponent(result.NAME) + '.php';
    return $.post(url, params, null, 'json');
});
// wait until all requests are done with $.when()
$.when.apply($, requests).done(function (responses) {
    responses.forEach(function (data) {
        // fill the data into the html
    });
});

请参阅 http://api.jquery.com/jquery.when/和相关页面,尤其是 http://api.jquery.com/category/deferred-object/。

您可以按照以下思路执行一些操作(尚未测试代码):

function doIteration(done, i){
    if(i <= 0){ done(); return; }
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4)
        {
            if(xmlHttp.status == 200){
                // Process response...
                console.log(xmlHttp.responseText);
                // Do next iteration.
                doIteration(done, --i);
            } else {
                doIteration(done, 0);
            }
        }
    };
    xmlHttp.open("method", "script.php");
    xmlHttp.send(null);
}
doIteration(function(){
    alert("Done loop!");
}, 10);

编辑:没有意识到您正在使用jQuery,只需将xmlHttp请求替换为$.ajax并启用async