JQuery使用deferreds串行多个ajax请求

本文介绍了一种使用JQuery实现多个Ajax请求串行执行的方法。通过promisedefer模式将所有Ajax请求放入数组中,并利用$.when.apply().done()确保它们按顺序执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用JQuery对多个ajax请求串行执行。

HTML代码:

<a href="#">Click me!</a>
<div></div>

JS:

复制代码
function GetSomeDeferredStuff() {
    var deferreds = [];

    var i = 1;
    for (i = 1; i <= 10; i++) {
        var count = i;

        deferreds.push(
        $.post('/echo/html/', {
            html: "<p>Task #" + count + " complete.",
            delay: count
        }).success(function(data) {
            $("div").append(data);
        }));
    }
    
    return deferreds;
}

$(function() {
    $("a").click(function() {
        var deferreds = GetSomeDeferredStuff();

        $.when.apply(null, deferreds).done(function() {
            $("div").append("<p>All done!</p>");
        });
    });
});
复制代码

  方法类似于Node.js中的q,使用promise defer模式将所有的ajax请求放到一个数组里,然后通过$.when.apply().done()将所有ajax请求依次执行。

这里的apply不是when专用的方法,而是需要将一个数组转化为某个方法的多个参数时可以用到的

The apply() method calls a function with a given this value, and arguments provided as an array (or an array-like object).

Note: While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.


var numbers = [5, 6, 2, 3, 7];

var max = Math.max.apply(null, numbers);

console.log(max);
// expected output: 7

var min = Math.min.apply(null, numbers);

console.log(min);
// expected output: 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值