传递一个函数,该函数使ajax请求在.done时为$.when

passing a function which makes ajax requests to $.when .done

本文关键字:函数 请求 ajax done when 时为 一个      更新时间:2023-09-26

我想动态生成ajax请求,但我想确保在它们全部完成后得到回调,所以我想将它们封装在.wwhen.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请求永远不会通过。有什么想法吗?

您将一个函数传递给$.when,而您应该传递一个或多个Deferred。您可以用延迟填充数组,并将其作为参数传递给$.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');
});

是否必须将"done"逻辑作为成功函数放入$.ajax调用参数中?我的意思是:

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

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