Ale*_*lex 31 jquery jquery-deferred
我在使用jQuery.when()在调用另一个函数之前等待多个ajax请求完成时遇到了问题.
每个ajax请求都会获得JSON数据,看起来像这样:
function loadData(arg){
var ajaxCall = $.ajax(
URL // depends on arg
)
.error( .... );
return ajaxCall;
}
Run Code Online (Sandbox Code Playgroud)
调用请求时,返回值(ajaxCall)将添加到名为ajaxRequests的列表中.
ajaxRequests = [];
ajaxREquests.push(loadData(arg))
Run Code Online (Sandbox Code Playgroud)
当所有请求都已完成后,我正在尝试将ajaxRequests传递给$ .when,以便等待所有请求完成.
var defer = $.when.apply($, ajaxRequests);
defer.done(function(args){
for (var i=0; i<args.length; i++){
inst.loadData($.parseJSON(args[i].responseText));
}
inst.draw();
});
Run Code Online (Sandbox Code Playgroud)
inst是一个基于JSON数据加载和绘制图形的对象.
问题是它似乎并没有真正等待请求完成 - args [i]是一个对象,但是当代码运行时,responseText是未定义的.如果我保存args [i]并稍后从控制台访问它,它可以工作.
我怀疑这个问题与使用.when和任意数量的参数有关,因为我在网上看到的所有例子都给它一个预定义的参数列表.
我不确定使用apply是否是正确的想法,但无论哪种方式它都无法正常工作并且行为不正常(依赖于浏览器).
任何帮助将不胜感激.
如果需要更多信息,请告诉我.
我正在使用jQuery 1.5
And*_*man 36
尽管亚历克斯确实为他的问题提供了解决方案,但我发现它有点困难.我有一个类似于他的问题,我解决了,我想与其他需要处理可变数量的ajax请求的人分享我的解决方案.
// Array of requests
var requests = Array();
requests.push($.get('responsePage.php?data=foo'));
requests.push($.get('responsePage.php?data=bar'));
var defer = $.when.apply($, requests);
defer.done(function(){
// This is executed only after every ajax request has been completed
$.each(arguments, function(index, responseData){
// "responseData" will contain an array of response information for each specific request
});
});
Run Code Online (Sandbox Code Playgroud)
除了Andy Corman的答案(我还是无法回复帖子,我认为......),如果你只有一个请求,响应信息将直接传递给defer.done - 函数作为参数; 所以你需要为这种情况提供一个if:
// Array of requests
var requests = Array();
requests.push($.get('responsePage.php?data=foo'));
var defer = $.when.apply($, requests);
defer.done(function(){
// This is executed only after every ajax request has been completed
if (requests.length == 1)
// "arguments" will be the array of response information for the request
else
$.each(arguments, function(index, responseData){
// "responseData" will contain an array of response information for each specific request
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10159 次 |
| 最近记录: |