作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我编写的最简单的代码,后端有一个简单的 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/
我正在用 python 编写一个猜词游戏。这是我的学校项目。我快完成了,我只是有一件事有问题。我不知道如何掩盖一个词。例如,如果单词是 monkey,程序应该显示 ------ 并且当用户猜一个字母时
我是一名优秀的程序员,十分优秀!