dou29106 2014-09-30 13:57
浏览 49

我试图在用户关闭浏览器时运行.php脚本

So im making a game lobby atm and want to run a .php script if a user closes or refreshes his browser.
My problem is, the .unload doesn't even fire, but it should, I basicly used the exact same thing in the wiki. What did I do wrong?

My index:

<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>

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

?>

  • 写回答

1条回答 默认 最新

  • dongque6377 2014-09-30 14:23
    关注

    IMO the only solution is to send some heartbeat signal every N seconds. If the heartbeat stops - user has closed the browser. There is no reliable JS event for browser closing. You can show a message with onbeforeunload event but you don't have enough time to send an ajax from that callback. If this callback does not return in a 1ms or so the page will just close. It is made this way because if a user enters a malicious page and wants to close it, the page won't be able to run some infinite loop in onbeforeunload callback to prevent the user from closing the page.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。