只有在完成了多个AJAX请求后触发功能多个、完成了、功能、AJAX

2023-09-11 00:34:35 作者:时光,你很欠抽

我有一个特别的功能,我想运行一次,并且只有在完成一些AJAX请求后。

I've got a particular function I want to run once, and only after the completion of several AJAX requests.

我目前的解决方案看起来有点像这样的:

My current solution looks a bit like this:

function doWork() {
    //This is the function to be run once after all the requests
}

//some tracking/counting variables
var ajaxDoneCounter = 0;
var numOfAjaxRequests = 5;
var workDone = false;

function doWorkTrigger() {
    ajaxDoneCounter++;
    if( !workDone && ajaxDoneCounter >= numOfAjaxRequests ) {
        workDone = true;
        doWork();
    }
}

// ...

//and a number of ajax requests (some hidden within functions, etc)
//they look something like this:
$.ajax({
    url: "http://www.example.com",
    dataType: "json",
    success: function( data ) {
        //load data in to variables, etc
        doWorkTrigger();
    }
});

在上面的一个明显缺陷是任何AJAX调用不成功也不会增加 ajaxDoneCount 的doWork()可能永远不会被调用。我能得到周围使用错误回调中的任何 $。阿贾克斯,这样就不会担心我太多。

One obvious pitfall in the above is that any AJAX call that is not successful will not increment ajaxDoneCount and so doWork() will probably never be called. I can get around that using the error callback in inside any $.ajax, so that doesn't worry me too much.

我想知道的是以上是否是安全的和/或好的做法呢? 是否有一个把戏我已经错过了,或者任何其他的事情可能更好地工作?

What I want to know is whether the above is safe and/or good practice? Is there a trick I've missed, or any thing else that might work better?

推荐答案

更新:由于jQuery的1.5,的 延迟对象的 [文档] 提供了一个清晰的解决方案。 Have来看一个例子这里。

Update: Since jQuery 1.5, deferred objects [docs] provide a cleaner solution. Have a look at an example here.

我会用 .ajaxComplete() ,它会被触发每当一个Ajax调用完成(成功或错误):

I would use .ajaxComplete(), it will be triggered whenever an Ajax call completed (success or error):

var numOfAjaxRequests = 5;

$(document).ajaxComplete(function() {
    numOfAjaxRequests--;
    if(!numOfAjaxRequests) {
        doWork();

    }
});

然后,你不必编辑每一个Ajax请求。

Then you don't have to edit every Ajax request.

您甚至可以使用 .ajaxSend() 得到通知,而不是硬编码开始Ajax请求的,(但我不知道这是否真的有效,也许你会遇到竞争条件):

You could even use .ajaxSend() to get notified of starting Ajax requests, instead of hardcoding it (but I am not sure whether this really works, maybe you will experience race conditions):

var numOfAjaxRequests = 0;

$(document).ajaxSend(function() {
    numOfAjaxRequests++;
});
 
精彩推荐
图片推荐