gpt4 book ai didi

javascript - 检查所有 Ajax 请求何时完成 - 纯 JavaScript

转载 作者:行者123 更新时间:2023-11-28 00:58:14 25 4
gpt4 key购买 nike

我知道jQuery's ajaxStop方法。

$(document).ajaxStop(function() { //Do something });

如果 jQuery 不可用,有没有办法用纯 JavaScript 来做到这一点?

如果是这样,您能举个例子吗?

干杯

最佳答案

很好,我会咬(尽管你甚至不尝试也很懒):

来自jQuery docs :

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event. Any and all handlers that have been registered with the .ajaxStop() method are executed at this time.

那么你需要什么?嗯:一个中央 API(某种模块),您将使用它来执行 AJAX 请求。在本模块中,您必须跟踪待处理的请求,并在请求终止后将其删除。
如果队列(可以这么说)为空,那么您可以检查 ajaxStop 队列中是否有任何已注册的回调,并调用它们。

基本设置(伪代码)如下所示:

var myAjax = (function()
{//create closure scope to track ajax requests
var activeRequests = [],
stopQueue = [],
ajaxModule = {},//the module itself
createXhr = function(){};//function to create XHR requests
ajaxModule.ajax = function(params, callback)
{
var xhr = createXhr(params),
key = activeRequests.length;
activeRequests.push(xhr);//add to active array
xhr.onreadystatechange = function()
{//assign internal handler
if (this.readyState === 4 && this.status === 200)
{
//invoke passed callback only if request is done
callback.call(this, []);//pass params as you please
activeRequests.filter(function(e)
{
return e !== this;
}, this);//define this callback in closure, of course
if (activeRequests.length === 0)
{//no more active requests
stopQueue.map(function(callback)
{
callback();//invoke callbacks
});
}
}
};
};
return ajaxModule;//expose module
}());

当然,您仍然需要实现管理 stopQueue 回调的函数,并且您必须自己实现可靠的 AJAX 模块,但这是您可以使用的简单设置。

关于javascript - 检查所有 Ajax 请求何时完成 - 纯 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25971224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com