如果用户关闭浏览器,我将尝试运行一个.php脚本


Im trying to run a .php script if a user closes his browser

所以我正在制作一个游戏大厅atm,如果用户关闭或刷新浏览器,我想运行一个.php脚本
我的问题是,unload甚至不会启动,但它应该启动,我在wiki中基本上使用了完全相同的东西。我做错了什么?

我的索引:

<script type="text/javascript">
jQuery(document).ready(function ($) {
    $(window).on('beforeunload', function() {
        return "Do you really want to leave this lobby?";
    });
    $(window).unload(function() {
        alert("wat");
        xmlhttp.open("POST","test_ajax.php",true);
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("session=test");
    });
});
</script>

我的test_ajax.php:

<?php
$db_name = "test";
$db_username = "root";
$db_password = "";
$db_host = "localhost";
mysql_connect($db_host, $db_username, $db_password) or die ("No connection possible!");
mysql_select_db($db_name) or die ("No database found!");
$v = "Testaccount";
$sql = mysql_query("UPDATE users SET Avatar=1 WHERE Username='$v'");

?>

IMO唯一的解决方案是每N秒发送一次心跳信号。如果心跳停止-用户已关闭浏览器。浏览器关闭没有可靠的JS事件。您可以显示带有onbeforeunload事件的消息,但您没有足够的时间从该回调发送ajax。如果这个回调在1ms左右没有返回,页面将关闭。这样做是因为,如果用户进入恶意页面并想关闭它,该页面将无法在onbeforeunload回调中运行一些无限循环来阻止用户关闭该页面。