Javascript同步AJAX超时

发布于 2024-08-22 00:16:21 字数 553 浏览 3 评论 0原文

当页面关闭时,我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仅冇旳回忆 2024-08-29 00:16:21

您的问题是浏览器冻结,您试图通过手动循环冻结浏览器来解决它。这也会冻结 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 hidden DIV, with their src properties set to the URL you want to request.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文