如果之后更改了网页位置,则不会发送XMLHttpRequest

时间:2015-09-04 22:59:30

标签: 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请求的任何想法?

1 个答案:

答案 0 :(得分:1)

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