問題描述
如果用戶導航到另一個頁面,我想中止一些(可能)長時間運行的 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.
這篇關于即使在調用 abort (jQuery) 之后,瀏覽器也會等待 ajax 調用完成的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!