weixin_33682719 2015-04-09 15:38
浏览 32

按顺序运行Ajax

Just wondering how to make sure Ajax in for loop returns values in order. For example, I have this code:

for(var i=0; i < list.length; i++) {
  $.ajax({
    url: ...,
    type: 'get',
    dataType: "jsonp",
    success: function(data) {
      ...
      var html = '...';
      $('#some-div').append(html);
    })
}

And when I run it, result sometimes run in right order, but sometimes it doesn't. I don't know what to do. Please someone helps me fix this problem. Thanks!

  • 写回答

2条回答 默认 最新

  • 三生石@ 2015-04-09 15:40
    关注

    They don't return in order, and that is out of your control unless you queue the calls sequentially (which will slow down the whole process) but that does not mean you can't assemble the results in the correct order.

    Add a scoping function and use a temp container appended immediately (in order) and filled in later after the Ajax completes:

    for(var i=0; i < list.length; i++) {
      function(i){
          var $div = $('<div>');
          $('#some-div').append($div);
          $.ajax({
           url: ...,
           type: 'get',
           dataType: "jsonp",
           success: function(data) {
             ...
             var html = '...';
             $div.append(html);
        })
      }(i);
    }
    

    The scoping function gets immediately executed, passing i as a local i parameter (if needed). This is what they call an IIFE (Immediately Invoked Function Expression).

    Alternatively, you can then use the value of i to determine where in sequence to insert the particular result. Personally I like the first "placeholder" option.

    Note: As @Rooster points out, you are often better off making a single Ajax call that returns multiple items (already in sequence).

    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试