如何触发功能时,所有的Ajax完成? [英] How to trigger a function when all ajax finish?

查看:104
本文介绍了如何触发功能时,所有的Ajax完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ajax请求会被用户点击来启动

ajax request will be initiated by user click

这是不可能知道有多少请求将被发送

It is impossible to know how many request will be sent

我试过ajaxComplete,但它不工作,我想在页面加载后,不能检测到阿贾克斯。

I tried ajaxComplete, but it is not work, I think it cannot detects ajax after the page loaded.

function ajax1() {
    $.ajax({
        url: 'getCount.php',
        type: 'GET',
        dataType: 'html',
        success: function (data) {
            var count = parseInt(data);
            for (var i = 0; i < count; i++) {
                ajax2();
            }
        }
    });
}

function ajax2() {
    $.ajax({
        url: 'getCount2.php',
        type: 'GET',
        dataType: 'html',
        success: function (data) {
            var count = parseInt(data);
            for (var i = 0; i < count; i++) {
                ajax3();
            }
        }
    });
}

function ajax3() {
    $.ajax({
        url: 'ajax3.php',
        type: 'GET',
        dataType: 'html',
        success: function (data) {
            //do something
        }
    });
}
$(document).ajaxComplete(function (event, xhr, settings) {
    alert('Complete');
});

推荐答案

更​​新:真的很好看的诺言:承诺菜谱

UPDATE: Really good read on promises: Promises cookbook

这样做的一般方法是使用由 $返回的承诺。AJAX 的功能。

Normal way of doing that is using promises returned by $.ajax function.

改变你的函数返回阿贾克斯调用的结果是:

Change your functions to return result of .ajax call:

function ajax1(..) { 
  return $.ajax(...)
}

然后使用 $。当进行解决时,所有的承诺都解决了新的希望。

Then use $.when to make new promise resolved when all promises are resolved.

$.when([ajax1(), ajax2(), ajax3()]).then(function() { alert('all complete') })

然而,在更复杂的情况下(这是你的),你需要动态存储引用的所有承诺,并只调用 $。当一旦所有的承诺补充说。

However in more complicated case (as is yours) you need to dynamically store references to all promises and only call $.when once all the promises added.

因此​​,举例来说,你可以创建承诺,一个是 ajax2 电话和一个用于 ajax3 呼叫数组。

So for instance you can create to arrays of promises, one for ajax2 calls and one for ajax3 calls.

var ajax2calls = [], ajax3calls=[]  

function ajax1() {
  return $.ajax({
    url: 'getCount.php',
    type: 'GET',
    dataType: 'html',
    success: function (data) {
        var count = parseInt(data);
        for (var i = 0; i < count; i++) {
            ajax2calls.push(ajax2());
        }

        $.when(ajax2calls).then(function() {
            $.when(ajax3calls).then(function() {
               alert('all done')
            }
        })

    }
  });
}

另外,你可能要考虑使用蓝鸟承诺库,因为它提供了很多比普通的承诺/ A或承诺/ A +更丰富的API。检查地图结算所有方法等。

Also, you might want to consider using Bluebird promise library, as it provides a lot more rich API than regular promise/A or promise/A+. Check map, settle, all methods etc.

这篇关于如何触发功能时,所有的Ajax完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆