简体   繁体   English

jquery ajax()async false

[英]jquery ajax() async false

i have problem.. 我有问题..

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

}
 $("div").click(function(){
        alert("it works");
 });

problem is: is I didn't put there async: false data from file.php are only in last div so with id 9 but now there is async: false - so data are in every div so that is good 问题是:我没有把async: false放在那里async: false来自file.php的 async: false数据只在最后一个div中,所以id为9,但现在有async: false - 所以数据在每个div中都是好的

but if i want click while it was loading by ajax it doesn't work (only after finished all ajax-es) 但是,如果我想通过ajax加载时点击它不起作用(仅在完成所有ajax-es之后)

how resolve this problem? 怎么解决这个问题? (maybe the false is that am I using ajax. I can use getJSON ect..) (也许错误的是我使用的是ajax。我可以使用getJSON等...)

thanks for helping 谢谢你的帮助

If you want the user to be able to use the interface while the ajax call is running, you should change your async to true . 如果您希望用户在ajax调用运行时能够使用该接口,则应将async更改为true It has also been noted by James Allardice that in this scenario you need to use a javascript closure to retain the value of your original id for when the ajax call is returned. James Allardice也注意到,在这种情况下,您需要使用javascript闭包来保留返回ajax调用时原始id的值。 For more information regarding javascript closures check out how-do-javascript-closures-work , a really good question found here on stackoverflow. 有关javascript闭包的更多信息,请查看how-do-javascript-closures-work ,这是一个在stackoverflow上找到的非常好的问题。

for(id = 1; id < 10; id++){
    $(".div").append("<div id='" + id + "'></div>");

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

A good solution to this is to use a recursive function. 一个很好的解决方案是使用递归函数。

function appendDivs(limit, count) {
    count = count || 1;
    if (count <= limit) {
        $(".div").append("<div id=" + count + "></div>");
        $.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);

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

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