阿贾克斯jQuery的多个呼叫在同一时间 - 长的等待答案,不能够取消 [英] Ajax jQuery multiple calls at the same time - long wait for answer and not able to cancel
问题描述
我的问题如下:
- 在一个页面上,我做多(6)AJAX调用(通过jQuery)来获取,同时一些数据(使用PHP包装器来获取通过调用数据)
- 的请求在同一时间做,这需要他们10-20秒即可完成
- 如果用户点击任何链接,去别的地方(到其他页),我可以看到,所有未完成的呼叫被取消
- 然而,浏览器仍在等待20秒以导航到其他页面 - 它就像它仍在等待最长的呼叫来完成的,即使它被取消
(同样的问题发生在Chrome和Firefox,AJAX调用是异步的......我试图设置ajax的超时时间,捕捉到的readyState = O的Ajax错误的反应,甚至试图做一些与webworkers,但没有成功)
(Same issue is happening in Chrome and Firefox, ajax calls are asynchronous...I have tried to set ajax timeout, to capture readystate=o in ajax error response, even tried to do something with webworkers, to no avail)
任何有识之士将是有益的。
Any insight would be helpful
谢谢!
推荐答案
这是由于的最大连接数
浏览器到一个域。
That is due to the maximum number of connections
of the browser to a single domain.
请参阅 Browserscope 为每个浏览器mamimum。
See Browserscope for mamimum per browser.
- 在IE 8 + 9:6的连接
- 在IE 10:8的连接
- 在Chrome浏览器26:6的连接
- 火狐21:6的连接
你可以做的就是收集所有Defferred对象,并取消他们的时候使用点击一个链接。
What you could do is collect all Defferred objects and cancel them when the use clicks on a link.
例如:
// some ajax calls
doAjax({});
doAjax({});
var requests = [];
// helper function to perform and register calls
function doAjax(options) {
var jqXHR= $.ajax(options);
requests.push(jqXHR);
jqXHR.always(function(jqXHR) {
var index = requests.indexOf(jqXHR);
if (index!=-1) {
requests.splice(index, 1);
}
});
}
// function to abort all calls
// when your application has a router to provide navigation, this function
// is typically called when you navigate to another page
function abortAllPendingRequests() {
var i;
for (i=0; i<requests.length; i++) {
var xhr = requests[i];
// already finished calls (readyState 4) should not be aborted
if (xhr.readyState != 4) {
xhr.abort();
}
}
};
所有剩下的就是调用 abortAllPendingRequests
功能,当用户尝试导航到另一个页面。
All is left is calling the abortAllPendingRequests
function when the user tries to navigate to another page.
当你有某种路由器
(如 Backbone.Router ),你可以调用它。
When you have some sort of router
(e.g. Backbone.Router) you could call it there.
如果您的应用程序没有一个路由器
用于导航,但你使用普通的锚链接,您可以添加一个onClick到调用<$ C链接$ C> abortAllPendingRequests 的功能。
If your application does not have a router
for navigating, but you make use of plain anchor links, you could add an onClick to the links which calls the abortAllPendingRequests
function.
这篇关于阿贾克斯jQuery的多个呼叫在同一时间 - 长的等待答案,不能够取消的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!