weixin_33734785 2012-02-16 21:25 采纳率: 0%
浏览 45

jQuery等待Ajax响应

I have the following code:

    for (i=1;i<=pages;i++) {
        $('#procout').append(Processing Page#"+i+"<br />");
        $.ajax({
            url: 'processor.php',
            data: {storen: perpage, pagen : i},
            success: function(data) {
                $('#procout').append(data+"<br />");

            }
        });
    }

What I am trying to do is make the script wait for the Ajax response after every loop. Instead it prints out the "Processing Pages" lines all together and the the Ajax responses from each run in the order the server responds (out of order). I tried setting the async option to false, but that simply causes the JS to wait until all six requests are done and then output everything from all runs together.

Note: The values of the pages, perpage, and pagen are irrelevant to the issue.

  • 写回答

1条回答 默认 最新

  • larry*wei 2012-02-16 21:29
    关注

    Since you've already tried making the ajax requests async:false (which is seldom if ever a good idea anyway), consider breaking your loop body into a function that makes the ajax request, and then runs the next request in the callback:

    function runRequest(num){
        if (num > pages) return; //since your original was looping while i <= pages
    
        $('#procout').append("Processing Page#" + num + "<br />");
        $.ajax({
           url: 'processor.php',
           data: {storen: perpage, pagen : num},
           success: function(data) {
               $('#procout').append(data + "<br />");
    
               runRequest(num + 1);
           }
        });
    }
    

    And then of course starting the process off with

    runRequest(0);
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!