javascript - 如果网页位置随后更改,则不会发送 XMLHttpRequest

标签 javascript ajax xmlhttprequest

在某些时候,我的网页正在更改其 location.href,导致浏览器导航到另一个页面。

我想在更改页面之前执行 XHR POST 请求。 我宁愿不等待此 XHR 请求完成,因为未收到 100% 的请求是可以的,但速度至关重要。

我尝试了这段代码,但是XHR 请求不是由 Firefox/Chrome 发送的,因为 location.href 之后立即发生了更改

<html>
<head></<head>
<body>

This is page test1.htm<br>
<input type="button" value="Go!" onclick="go();">

<script>
function go() {
    xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() { /* Do nothing */ };
    xhr.open('POST', '/cgi-bin/hb.exe?action=remoteapppost', true);
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send('action=remoteapppost&id=TEST');

        // ==> this XHR request is NOT sent because of the following line:

    location.href = "test2.htm";
}
</script>
</body>
</html>

如果我在回调中设置断点或移动 location.href = "..."; ,一切都会正常工作(当然)。

知道如何在离开网页之前发送 XHR 请求吗?

最佳答案

您想要结合使用 beforeunload 事件和新的 navigator.sendBeacon() API(旨在不阻止导航)。

关于javascript - 如果网页位置随后更改,则不会发送 XMLHttpRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407676/

相关文章:

javascript - 如何在 react native android中获取响应 header ?

javascript - XMLHttpRequest 调用不包含 If-Modified-Since header

javascript - ajax调用没有命中断点,但继续成功函数

jquery - CORS 与 jQuery.ajax()

javascript - 单击鼠标从预加载播放随机声音文件(mp3 文件)

javascript - 使用 php 和 html 关注/取消关注按钮

javascript - 变量超出精确选择 - Javascript/Ajax

php - Codeigniter: 'You did not select a file to upload',当通过 Ajax 发送数据时

javascript - AngularJS PDF 查看器无法在 IE 中运行

javascript - 为什么在创建包时必须在 webpack 配置中将我的 peerDependencies 列为外部?