即使在调用 abort (jQuery) 之后,浏览器也会等待 ajax 调用完成
如果用户导航到另一个页面,我想中止一些(可能)长时间运行的 ajax 调用.以下 jQuery 代码在离开页面时对所有待处理的 XMLHttpRequest 对象调用 abort:
I have some (potentially) long-running ajax calls that I would like to abort if the user navigates to another page. The following jQuery code calls abort on all pending XMLHttpRequest objects upon navigating away from the page:
$.ajaxSetup({
beforeSend: function(xhr) {
$(window).bind('beforeunload', function() {
xhr.abort();
});
}
});
在一个测试用例中,我强制等待被调用的服务器端操作等待 10 秒.使用 Firebug,我确认当我单击页面上的任何链接时,上述代码确实会导致所有挂起的 ajax 调用立即停止.但是,浏览器仍会等待整整 10 秒,然后才能转到下一页.IE 似乎表现出相同的行为.这是已知的浏览器行为吗?在这种情况下,我能做些什么让用户立即离开页面?提前致谢.
In a test case, I force a 10-second wait on the server-side operation being called. Using Firebug, I confirmed that the above code does indeed cause all pending ajax calls to halt immediately when I click any link on the page. However, the browser still waits the full 10 seconds before moving on to the next page. IE appears to exhibit the same behavior. Is this a known browser behavior? Is there anything I can do allow the user to navigate away from the page immediately in this situation? Thanks in advance.
推荐答案
感谢您的回复!事实证明,我完全错误地认为这是一个浏览器问题——问题出在服务器上.ASP.NET 对需要会话状态的同一会话的请求进行序列化,因此在这种情况下,直到那些由 ajax 发起的请求完成后,下一页才开始在服务器上处理.
Thank you for your replies! It turns out I was completely wrong about this being a browser issue - the problem was on the server. ASP.NET serializes requests of the same session that require session state, so in this case, the next page didn't begin processing on the server until those ajax-initiated requests completed.
不幸的是,在这种情况下,响应 ajax 调用的 http 处理程序需要会话状态.但是只读访问已经足够好了,因此通过使用 IReadOnlySessionState 而不是 IRequiresSessionState 标记处理程序,会话锁不会被持有并且问题得到解决.
Unfortunately, in this case, session state is required in the http handler that responded to the ajax calls. But read-only access is good enough, so by marking the handler with IReadOnlySessionState instead of IRequiresSessionState, session locks are not held and the problem is fixed.
希望这些信息对其他人有用.
Hope this information proves useful to others.
相关文章