jquery ajax()async false

我有问题..

for(a=1;a<10;a++){ $(".div").append("
") $.ajax({ url: "file.php", data: "a="+a, type: "POST", async: false, success: function(data) { $("#"+a).html(data); } }); } $("div").click(function(){ alert("it works"); });

问题是:我没有把async: false放在那里async: false来自file.php的 async: false数据只在最后一个div中,所以id为9但是现在有async: false – 所以数据在每个div中都是好的

但如果我想点击它是由ajax加载它不起作用(只有在完成所有ajax-es后)

怎么解决这个问题? (也许错误是我使用ajax。我可以使用getJSON等…)

谢谢你的帮助

如果您希望用户在ajax调用运行时能够使用该接口,则应将async更改为true 。 James Allardice也注意到,在这种情况下,您需要使用javascript闭包来保留返回ajax调用时原始id的值。 有关javascript闭包的更多信息,请查看how-do-javascript-closures-work ,这是一个在stackoverflow上找到的非常好的问题。

 for(id = 1; id < 10; id++){ $(".div").append("
"); (function(id) { $.ajax({ url: "file.php", data: "a=" + id, type: "POST", async: true, success: function(data) { $("#"+ id).html(data); } }); }(id)); }

一个很好的解决方案是使用递归函数。

 function appendDivs(limit, count) { count = count || 1; if (count <= limit) { $(".div").append("
"); $.ajax({ url: "file.php", data: "a=" + count, type: "POST", async: true, success: function(data) { $("#" + count).html(data); appendDivs(limit, count + 1); }, error: function(e) { alert('Error - ' + e.statusText); appendDivs(limit, count + 1); } }); } else { return false; } } appendDivs(10);