【问题标题】:Ajax loop and response orderAjax 循环和响应顺序
【发布时间】:2017-02-09 15:43:24
【问题描述】:

我正在使用 $.ajax 从服务器(地理服务器)检索一系列数据。

(简化的)请求如下所示:

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;
                  }
     })
});

我需要写入全局变量dataList,因为我需要在来自 urllist 的 所有 请求完成后触发一个事件。 (我已经实现了类似so 的延迟)。

问题在于完成的列表总是以不同的顺序排列。我需要结果与请求的顺序相同。

这可能是一个关闭问题,其中索引i 被传递给ajax 函数,而dataList 的分配在稍后发生(当每个循环继续进行时)。 我尝试像this 那样处理它,但问题仍然存在。同样$.each 就像上面的代码一样应该为每次迭代创建一个单独的闭包。

我已经成功实现了 recursive function,但它是同步的。

编辑:suggested duplicate 不处理循环的 ajax 请求

【问题讨论】:

  • “这可能是关闭索引的问题...”“我已经实现了类似的延迟” 嗯.. . 不,你不知道吗?你错过了 $.when 和回报。和延迟数组。
  • 我添加了一个带有建议的答案,但现在我仔细阅读,您想在所有请求完成且不正确时触发一个事件,因此我删除了。
  • @KevinB :“(简化的)请求如下所示:”。我故意省略了部分代码以保持帖子简短。检查我提供的链接。
  • 没有。你的问题需要有一个 mcve

标签: javascript jquery ajax geoserver


【解决方案1】:

您可以按正确的顺序访问$.when回调中的所有结果

// 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
});

【讨论】:

  • 这样我只会在结果中得到一个值。这就是为什么在成功处理程序中使用全局变量的原因。我可以用 $.when(deferreds[0]).then(function(data){value=data}) 得到一个值 有没有更简单的方法来访问 deferreds 中的数据?
  • 我刚刚用上面的方法检查了来自deferreds的值,顺序又是随机的
  • 好的,谢谢。我会将您的答案标记为正确,因为显然我的问题出在其他地方。由于这与现在的原始版本完全不同,因此我在这里创建了一个新问题:stackoverflow.com/questions/42161566/…
【解决方案2】:

问题与延迟无关,而是与请求所需的 jsonp 或相关 jsonpcallback 有关。以 json 格式请求数据解决了问题

感谢@charlietfl 的答案:Looped ajax request. Error handling and return order

对于查找此内容的任何人:您很可能必须启用 Cross-Origin Resource Sharing on geoserver 才能直接访问 JSON

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2018-05-18
    • 2012-05-02
    • 2010-12-17
    • 2014-02-26
    相关资源
    最近更新 更多