我正在做一个小游戏,我想在用户离开页面时保存分数,我想在没有jquery或其他库的情况下做到这一点,这可能吗?
我通过执行一个javascript函数来保存分数,该函数创建一个表单并自动提交它,这样它的数据就会被发送到服务器:
function sendData() {
var form = document.createElement("form");
form.setAttribute("method","post");
form.setAttribute("action", "submit.php");
form.setAttribute("id","returnForm");
var formContent1 = document.createElement("input");
formContent1.setAttribute("name","gamesPlayed");
formContent1.value = gamesPlayed; //parameter 1
var formContent2 = document.createElement("input");
formContent2.setAttribute("name","totalSteps");
formContent2.value = totalTurns; //parameter 2
form.appendChild(formContent1);
form.appendChild(formContent2);
document.body.appendChild(form);
document.getElementById("returnForm").submit();
}我发现了一些东西,比如,这个函数将弹出一个窗口,上面写着“你真的确定要离开这个页面吗”,
window.onbeforeunload = function(e) {
return false;
}但是,当我尝试将'sendData()‘函数放入其中时,它不起作用:
window.onbeforeunload = function(e) {
sendData();
}即使我把整个函数都放进去了:
window.onbeforeunload = function(e) {
var form = document.createElement("form");
form.setAttribute("method","post");
form.setAttribute("action", "submit.php");
form.setAttribute("id","returnForm");
var formContent1 = document.createElement("input");
formContent1.setAttribute("name","gamesPlayed");
formContent1.value = gamesPlayed; //parameter 1
var formContent2 = document.createElement("input");
formContent2.setAttribute("name","totalSteps");
formContent2.value = totalTurns; //parameter 2
form.appendChild(formContent1);
form.appendChild(formContent2);
document.body.appendChild(form);
document.getElementById("returnForm").submit();
}发布于 2017-07-15 19:19:58
在javascript中使用onunload事件,就像在this article中一样。
window.onbeforeunload = function(e) {
return 'Are you sure ?';
}
window.onunload = function () {
sendData();
}发布于 2017-12-28 01:11:24
这并不是对这个问题的直接回答,但它对我很有效:我没有在pageonunload上发送数据,而是尝试使用XMLHttpRequest以一定的间隔发送数据,这很好用。
https://stackoverflow.com/questions/45117339
复制相似问题