문제

Here's a minimum example -

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]", '');

When I open the webpage, a file is created with the count number as its name. When I close the tab jquery requests unloader.php which is just a standalone script that creates a file with the count number as its name too.

Sometimes it works, sometimes it doesn't. I mean the opening file is always created. But sometimes the file which has to be created on closing is not made. Any idea where the issue occured ?

도움이 되었습니까?

해결책

You can't (reliably) make AJAX calls when unloading the page. Because it's being unloaded, anything still in progress will be dropped.

If the browser's fast enough with the AJAX call (or the server's slow enough in responding to the new page load) then you should see a result, but it is not at all reliable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top