這裏有一個最小的例子 -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