1

我想即时生成 ajax 请求,但我想确保在它们全部完成后得到回调,所以我想将它们包装在 .when .done 语句中,如下所示:

$.when(function(){
        $.each(oOptions, function(){
            var filePath = this.filePath,
            dataType = this.dataType;

            $.ajax({
                url : filePath,
                dataType : dataType
            });
        });
    })
    .done(function(){
        console.log('success');

        console.log(arguments);
    })
    .fail(function(){
        console.log('failed');
    });

我的选项是一个对象数组,其中包含我想同时发出的每个 ajax 请求的文件路径和数据类型。此代码将返回成功,但参数只是一个函数,ajax 请求永远不会通过。关于如何做到这一点的任何想法?

4

2 回答 2

1

您不必将“完成”逻辑作为成功函数放入 $.ajax 调用参数中吗?我的意思是这样的:

$.ajax({
  url : filePath,
  dataType : dataType,
  success: function(){
    console.log('success');
  }
});

由于 ajax 调用是异步进行的,所以可以在 ajax 调用完成之前调用 done()...

于 2012-02-08T15:34:23.880 回答
1

您将一个函数传递给$.when,而您应该传递一个或多个Deferreds。您可以用延迟填充数组并将其$.when作为参数传递:

var deferreds = [];

$.each(oOptions, function() {
    var filePath = this.filePath,
    dataType = this.dataType;

    deferreds.push($.ajax({
        url : filePath,
        dataType : dataType
    }));
});

// use the array elements as arguments using apply
$.when.apply($, deferreds)
.done(function(){
    console.log('success');

    console.log(arguments);
})
.fail(function(){
    console.log('failed');
});
于 2012-02-08T15:36:24.693 回答