weixin_33721427 2017-02-09 15:43 采纳率: 0%
浏览 51

Ajax循环和响应顺序

I am retrieving a series of data from a server (geoserver) using $.ajax.

The (simplified) request looks like this:

var dataList=[];
//var urllist= // a list of several URLs to request data from


$.each(urllist,function(i) {
    $.ajax({
         jsonpCallback: 'getJson',
         type: 'GET',
         url: urllist[i],
         dataType: 'jsonp',
         success: function(data) {
                    dataList[i]=data.value;
                  }
     })
});

I need to write to the global variable dataList because I need to fire an event after all requests from urllist are finished. (I've got deferreds implemented like so).

The problem is that the finished list is always in a different order. I need the result to be in the same order as the requests.

It might be a problem of closure where the index i that is passed on to the ajax function and the allocation to dataList that is happening at a later point (when the each loop has moved on). I tried taking care of that like this but the problem remains the same. Also $.each like in the code above should create a seperate closure for every iteration anyway.

I've managed to implement a recursive function but its synchronous.

edit: suggested duplicate does not deal with looped ajax requests

  • 写回答

2条回答 默认 最新

  • weixin_33739541 2017-02-09 15:52
    关注

    You can access all the results in $.when callback in the correct order

    // map an array of promises
    var deferreds = urllist.map(function(url){
        // return the promise that `$.ajax` returns
        return  $.ajax({         
             url: url,
             dataType: 'jsonp'
         }).then(function(data){
             return data.value;
         })
    });
    
    $.when.apply($, deferreds).then(function(results){
        // results will be array of each `data.value` in proper order
        var datalist = results;
        // now do whatever you were doing with original datalist
        $.each(datalist....
    
    }).fail(function(){
        // Probably want to catch failure
    }).always(function(){
        // Or use always if you want to do the same thing
        // whether the call succeeds or fails
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”