gpt4 book ai didi

javascript - 考虑浏览器连接限制的ajax请求超时

转载 作者:行者123 更新时间:2023-12-03 05:00:31 25 4
gpt4 key购买 nike

我遇到了具有固定超时的 ajax 请求的问题。所以我只是使用这个简单的代码。

$.ajax({
url: "test.html",
error: function(){
//do something
},
success: function(){
//do something
},
timeout: 7000
});

在我的场景中,可能会同时调用 20 个 ajax 请求,每个请求的超时时间为 7 秒。您可能知道,每个浏览器都有不同的连接数限制。问题来了。由于连接限制,一些 ajax 请求正在排队,但超时计数已经开始。所以有些请求在到达服务器之前就已经超时了。是否有可能只有当请求真正传输到服务器时才会倒计时?

最佳答案

$.ajax 的快速而肮脏的“替换” - 仅涵盖您在示例中使用的内容,但它应该是“直接”替换

function betterAjax(options) {
var xhr = new XMLHttpRequest();
var setListener = function(which, fn) {
if (typeof fn == 'function') {
if (which == 'success') {
which = 'load';
}
xhr.addEventListener(which, fn);
}
}
xhr.open(options.method || 'GET', options.url);
setListener('success', options.success);
setListener('error', options.error);
if (options.timeout) {
xhr.timeout = options.timeout;
}
xhr.end();
}

这是我几年前写的东西的简化版本 - 基本上是 https://jsfiddle.net/jaromanda/wpkeet34/

关于javascript - 考虑浏览器连接限制的ajax请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42246918/

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