这里有一个最小的例子 -onbeforeunload似乎并不总是trigerred
的index.php
<?php
$count = file_get_contents("count.txt") + 0;
file_put_contents("$count.txt [loaded]", '');
file_put_contents("count.txt", $count + 1);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<main>
<p> hi there </p>
</main>
<script type="text/javascript">
var id = "<?php echo $count; ?>";
</script>
<script src="script.js"></script>
</body>
</html>
的script.js
$(document).ready(function()
{
$(window).bind('beforeunload', function() {
$.post("unloader.php", { id : id });
});
});
unloader.php
<?php
file_put_contents("$_POST[id] [unloaded]", '');
当我打开网页,文件与计数作为它的名称创建。 当我关闭该标签的jQuery请求unloader.php这仅仅是创建与计数作为其名称的文件过于独立的脚本。
有时工作,有时没有。 我的意思是始终创建开放文件。但是有时在关闭时必须创建的文件不会被创建。 任何想法发生问题的地方?
它,因为你绑定'onbeforeunload'事件到domready中函数内部很可能。如果放置内容的过程需要一段时间,那么当用户卸载页面时DOM可能没有准备好。 – BenM
@BenM可悲的是,我尝试了一个空白页并等待一段时间才结束。该文件有时不会在服务器上创建。 – user544262772
你能解释一下这一点吗?您只需在服务器上创建一个名为'$ _POST [id] [unloaded]'的空白文件?为什么不使用cookie或会话? – BenM