gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:43:34 24 4
gpt4 key购买 nike

在某些时候,我的网页正在更改其 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com