2016-01-26 18 views
1

我怎样才能让每一次迭代新AjaxCall的需要是异步。 不使用异步AjaxCall的在for循环中的Javascript

async: false, 

如果我这样做与异步I得到一个警告消息,我的UI冻结,我该如何解决这一问题?这不是循环正常

EDIT1

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; 
+0

所以你用的,而不是一个循环递归你可以调整你的代码。下一个函数调用(即迭代)取决于Ajax的成功回调。 – noahnu

+0

怎么能我能做到这一点?你可以用一个小例子来将EDIT1改为递归函数吗? –

+0

?你读过我的问题了吗? –

回答

1

你可以做这些方针的东西(没有测试的代码):

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请求,并留下启用async

+0

这个作品谢谢。 –

2

使用jQuery Ajax请求的承诺语义。

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/

+0

这将工作给我认为,但现在我要与其他解决方案马比以后,当完成程序完成我回来检查最快的方式感谢 –

+0

最快的方式?你在说什么? – Tomalak