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).

    评论

报告相同问题?