gpt4 book ai didi

javascript - 我猜 OnBeforeUnload 可以工作,但我只收到 50% 的数据

转载 作者:行者123 更新时间:2023-12-01 03:17:28 25 4
gpt4 key购买 nike

这是我编写的最简单的代码,后端有一个简单的 php api,它接收 get 参数并存储它。

<!DOCTYPE html>
<html>
<head>
<title>
test beforeunload
</title>
</head>
<body>



<script type="text/javascript">

function httpGetAsync(data){
theUrl='http://niteshchaudhry.com/ajay/api.php?name='+data;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET",theUrl, true);
xmlHttp.send(null);
}
function fireAsap(){
var elem=document.createElement('script');
elem.src='http://niteshchaudhry.com/ajay/api.php?name='+new Date();
document.getElementsByTagName('body')[0].appendChild(elem);
}
window.onbeforeunload = function(e) {
fireAsap();
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
};

</script>

</body>
</html>

问题是我在数据库中观察到,无论我使用 fireasap 还是 httpgetAsync 哪个函数,两次刷新或卸载后都会显示 1 个条目。谁能解释一下出了什么问题或者可以采取什么措施来获取每次刷新或卸载的数据

最佳答案

看看 navigator.sendBeacon(),它正是针对此用例而设计的。
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

常规请求的问题在于,无法保证浏览器实际上能够在页面卸载之前发送请求,这是在“尽力而为”的基础上完成的。 navigator.sendBeacon() 告诉浏览器在后台执行请求,与实际页面实例分开。这些请求始终是 POST 请求,因此您必须更改服务器端点以处理 POST 而不是 GET 请求。

navigator.sendBeacon() 尚未得到普遍支持,因此您需要使用常规请求作为后备解决方案。

关于javascript - 我猜 OnBeforeUnload 可以工作,但我只收到 50% 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45460252/

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