我想通过 ajax 发送 post 请求,它必须非常快,比如 100 毫秒以下。此页面还包含 setIntervals 中的其他网络请求(甚至图像刷新)。
当调用下面的函数 mainRequest()
时,我想停止所有其他网络请求并只发送此请求。所以它的快速和高优先级请求。
function mainRequest()
{
stop(); // something like this that stop all network requests immediately
$.post( "https://example.com", $str ,function(data) {
console.log(data);
})
.fail(function() {
alert( "error" );
});
}
我用谷歌搜索并找到了关于 request.abort();
的信息,是否有任何替代方法通常可以中止所有请求,包括图像加载。
最佳答案
我的解决方案是针对 XMLHttpRequests
请求。代码基于此 question and answers .
所以基本上你可以使用问题中解释的钩子(Hook)。
// Generate unique id
const generateUID = function () {
return `id:${Math.random().toString(36).substr(2, 9)}`;
};
// Where we store all requests
let requests = {};
// Intercept all XMLHttpRequest requests
(function (send) {
XMLHttpRequest.prototype.send = function (data) {
this.uid = generateUID();
requests[this.uid] = this;
this.addEventListener('readystatechange', function () {
if (this.readyState === 4) {
delete requests[this.uid];
console.log("Deleted", this.uid)
}
}, false);
send.call(this, data);
};
}(XMLHttpRequest.prototype.send));
// Call this to stop active requests
const stopActive = function () {
for (const key in requests) {
const request = requests[key];
console.log(request);
request.abort();
}
};
关于javascript - 在 jquery 中停止其他网络请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55036672/