jquery ajax() async false

后端 未结 2 1410
野趣味
野趣味 2021-01-01 23:19

i have problem..

for(a=1;a<10;a++){
    $(\".div\").append(\"
\") $.ajax({ url: \"file.php\",
相关标签:
2条回答
  • 2021-01-01 23:42

    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);
    
    0 讨论(0)
  • 2021-01-01 23:56

    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. 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. For more information regarding javascript closures check out how-do-javascript-closures-work, a really good question found here on 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));
    }
    
    0 讨论(0)
提交回复
热议问题