我正在做一个小游戏,我想在用户离开页面时保存得分,我想在没有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();
}
在onunload
中的javascript中使用this article事件。
window.onbeforeunload = function(e) {
return 'Are you sure ?';
}
window.onunload = function () {
sendData();
}
这不是问题的直接答案,但它对我有用:我没有在pageonunload上发送不起作用的数据,而是尝试使用XMLHttpRequest以间隔发送数据,这非常有效。