循环ajax请求。 error handling和退货订单

我正在使用$ .ajax从服务器(geoserver)检索一系列数据。 我需要在发生错误时重新运行请求,在完成所有操作时触发事件并能够以正确的顺序访问数据。

请求:

var dataAr=[] //Array to fill with data from server //var urllist= // an array of URLs to request data from var deferreds = []; // array to fill by ajax // looped ajax request $.each(urllist,function() { var url = this; deferreds.push( $.Deferred(function(deferred) { //wrap entire operation in another Deferred Object so i can rerun the request, see below $.ajax({ jsonpCallback: 'getJson', url: url, dataType: 'jsonp', tryCount : 0, retryLimit : 3, error: function(){ // rerun the request this.tryCount++; if (this.tryCount = this.retryLimit) { // reject if repeated requests fail deferred.rejectWith(this,[jqXHR, textStatus, errorThrown]); } }) } } }).then(function(data) { deferred.resolveWith(this, [data.value]); }) }).promise() ) }); 

在完整延迟数组上运行的成功和失败处理程序:

 $.when.apply($,deferreds) .then(function(data){ $.each(deferreds,function(i){ // not so pretty workaround to access all data in the deferreds, is there a better way? deferreds[i].then(function(data){dataAr[i]=data}) }) }) .fail(function(data){ }) 

实现此方法是为了能够重新运行请求并更改延迟状态。

请求和返回有效,但$.when回调的顺序不正确,每次重新运行整个代码时都会更改。

编辑:从服务器返回的JSON如下所示:

 parseResponse({"type":"FeatureCollection","totalFeatures":"unknown","features":[{"type":"Feature","id":"","geometry":null,"properties":{"GRAY_INDEX":12}}],"crs":null}) 

正如这里建议的那样,它的工作原理是将&format_options=callback:getJson到URL并将jsonpCallback: 'getJson'到请求中:

 getJson({"type":"FeatureCollection","totalFeatures":"unknown","features":[{"type":"Feature","id":"","geometry":null,"properties":{"GRAY_INDEX":12}}],"crs":null})