Javascript同步AJAX超时
当页面关闭时,我的 Javascript 需要向服务器发送一些数据,目前我使用 window.onbeforeunload
中的同步 AJAX (SJAX?) 请求来完成此操作。当然,这样做的问题是,如果我的服务器花费太长时间或网络连接中断,浏览器就会冻结。
据我所知,不可能为同步 AJAX 请求指定超时,并且异步 AJAX 请求在 window.onbeforeunload
上不起作用。我对如何解决此问题的最佳猜测是使用异步请求,然后锁定浏览器一段时间以使请求完成:
window.onbeforeunload = function() {
doSomeAjax(); // asynchronous request
var now = new Date();
var time_limit = now.getTime()+2000; // 2,000 ms
while(now.getTime() < time_limit) {
now = new Date();
}
}
这可行吗?这种方法有任何潜在的问题吗?
My Javascript needs to send some data to a server when the page closes, which I currently do with a synchronous AJAX (SJAX?) request in window.onbeforeunload
. The problem with this, of course, is that if my server takes too long or the network connection dies, the browser freezes.
From what I've read, it's not possible to specify a timeout for synchronous AJAX requests, and asynchronous AJAX requests don't work on window.onbeforeunload
. My best guess at how to solve this would be to use an asynchronous request, and then lock up the browser for some time to let the request finish:
window.onbeforeunload = function() {
doSomeAjax(); // asynchronous request
var now = new Date();
var time_limit = now.getTime()+2000; // 2,000 ms
while(now.getTime() < time_limit) {
now = new Date();
}
}
Would this work? Are there any potential issues with this method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题是浏览器冻结,您试图通过手动循环冻结浏览器来解决它。这也会冻结 UI 线程,所以这不是一个潜在的问题,而是一个明确的问题。
由于浏览器正在关闭,我想您不需要从 AJAX 响应接收任何反馈来更新正在关闭的页面?在这种情况下,也许您可以通过将
IMG
标签注入到隐藏的DIV
中来解决问题,并将其src
属性设置为您要请求的 URL。Your problem is that the browser freezes, and you're trying to solve it by manually freezing the browser in a loop. That will also freeze the UI thread, so that's not a potential problem, that's a definite problem.
Since the browser is closing, I guess you don't need to receive any feedback from the AJAX responses, to update the page being closed? In that case, perhaps you could solve your problems by injecting
IMG
tags into, say, a hiddenDIV
, with theirsrc
properties set to the URL you want to request.