[英]Javascript code not running onbeforeunload
我有3个变量来跟踪网站中的timepent
$_SESSION['checkin']; //logged when user first enters the site
$_SESSION['loggedAt']; //logged when the user leaves the site
$_SESSION['timespent']; //time spent in minutes
我想要做的是每次用户离开页面时,这些值都会被推送到数据库中。 我所做的是使用onbeforeunload。
以下是我使用它的方式:
在每个页面上:
<script type="text/javascript" src="js/storeSession.js"></script>
storeSession.js:
window.onbeforeunload = confirmExit();
function confirmExit()
{
var xhr = new XMLHttpRequest();
xhr.open('post','../php/storeSession.php',true);
xhr.send();
return "Are you sure you want to leave?";
}
和storeSession.php:
$_SESSION['loggedAt'] = time();
$temptime = (double)$_SESSION['timespent']/60;
$_SESSION['timespent'] = $_SESSION['loggedAt'] - $_SESSION['checkin'];
mysql_select_db($db, $conn) or die(mysql_error());
$data = mysql_query("INSERT INTO user (user_id, timespent) VALUES ($tempuser, $temptime) ON DUPLICATE KEY UPDATE timespent = timespent + $temptime")
or die(mysql_error());
$_SESSION['timespent'] = null;
$_SESSION['loggedAt'] = null;
$_SESSION['checkin'] = null;
mysql_close($con);
我找不到问题,一切似乎都运转正常(没有错误等)。 有人有什么主意吗?
一个问题是这一行:
window.onbeforeunload = confirmExit();
您调用了该函数并将返回值分配给window.onbeforeunload
,而不是分配函数本身。
将行更改为:
window.onbeforeunload = confirmExit;
......或使用封闭物。
你也在发送POST请求而不发送任何数据(你没有传递任何东西到send()
的第一个参数) - 你可能想要发出一个GET请求。
您需要从onbefore函数中删除括号
window.onbeforeunload = confirmExit;
您还要在确认之前结束与XHR呼叫的会话。 如果用户取消卸载,他仍然会被注销。
您是否尝试过使用onunload
而不是onbeforeunload
。 我记得后者是受限制的,因为它可能会被用来阻止用户退出页面(甚至是浏览器)。 我不完全确定,但我认为(大多数)浏览器只读取返回的字符串而忽略其余的。
另外,我自己在on(之前)卸载操作时遇到了一些问题,并通过显式使用与服务器的同步通信解决了这些问题(我使用了jquery + ajax),否则ajax请求没有完成(尽管我没有经验) XMLHttpRequest
,但我认为这个选项应该具有可比性)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.