我有3个变量来跟踪网站中的时间表
$_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);
我找不到问题,一切似乎都正常(没有错误等)。有没有人有任何想法?
答案 0 :(得分:2)
这一行存在一个问题:
window.onbeforeunload = confirmExit();
您调用了该函数并将返回值分配给window.onbeforeunload
,而不是分配函数本身。
将行更改为:
window.onbeforeunload = confirmExit;
...或使用封闭。
此外,您正在发送POST请求而不发送任何数据(您没有将任何内容传递给send()
的第一个参数) - 您可能希望改为发出GET请求。
答案 1 :(得分:1)
您需要从onbefore函数
中删除括号window.onbeforeunload = confirmExit;
在确认之前,您还将使用XHR呼叫结束会话。如果用户取消卸载,他仍然会被注销。
答案 2 :(得分:0)
您是否尝试过使用onunload
代替onbeforeunload
。我记得后者是受限制的,因为它可能会被用来阻止用户退出页面(甚至是浏览器)。我不完全确定,但我认为(大多数)浏览器只读取返回的字符串而忽略其余的字符串。
另外,我自己在on(之前)卸载操作时遇到了一些问题,并通过显式使用与服务器的同步通信解决了这些问题(我使用了jquery + ajax),否则ajax请求没有完成(尽管我有没有XMLHttpRequest
的经验,但我认为这个选项应该具有可比性)