dongmie3526 2018-10-20 01:41
浏览 73
已采纳

如何在页面关闭之前发送ajax数据?

I want to send a value to the database when the user closes the page such as online and offline , I hope to find the solution I have tried for more than 7 hours But does not work

<script tysssspe="text/javascript">
//ST
window.onbeforeunload = function(){
  var user_st = "0";
  $.ajax({
    type:"POST",url:"inc/offline.php",
    data:"user_st="+user_st
  });
}
//SD
</script>

To offline.php

<?php
tab
include "connect.php";
$UID = $_COOKIE["ID"];
$online_status = $_POST['user_st'];
$setStatus = $conn->prepare("UPDATE accounts SET online = :online_status WHERE id = :UID");
$setStatus->bindParam(':online_status',$online_status,PDO::PARAM_INT);
$setStatus->bindParam(':UID',$UID,PDO::PARAM_INT);
$setStatus->execute();
?>
  • 写回答

2条回答 默认 最新

  • dongqucheng3851 2018-10-20 08:29
    关注

    onbeforeunload will work in some browser (Chrome), but not in others. (Safari , FF and IE).

    There was a workaround is to make the ajax synchronous,

    window.onbeforeunload = function(){
      var user_st = "0";
      $.ajax({
        type:"POST",url:"inc/offline.php",
        data:"user_st="+user_st,
        async: false
      });
    }
    

    but Synchronous Ajax is deprecated. You can try if you can accept deprecated methods.

    If you doesn't require the online/offline to be 100% real time, one solution could be instead of reporting offline, let the user to report online (every 30 seconds, if server doesn't receive online update for more than 30 seconds, it treats this user as offline.) Potential disadvantage is that more db calls. (Do you need it to be persisted to database? Can it be in memcache? )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog