关闭选项卡后,更新数据库中的注销时间

时间:2019-03-06 06:04:58

标签: php jquery mysql ajax codeigniter-3

我的问题是,当用户关闭选项卡时,我必须调用ajax来更新数据库中的注销时间。因此,经过一些研究,我尝试使用下面的代码,但仍然无法正常工作。

我注意到了。在JS中添加以下脚本后,它会在20秒后自动注销。

我使用了下面的代码,但这不是SO用户团队建议的正确代码。

window.onbeforeunload = function(){
  // var msg="Are you sure want to close this tab";
  // return msg;
     $.ajax({
       method:"POST",
       async: false,
       url:baseUrl+"/Employee_control/logoutTimeUpdate"
   });

所以我将其更改为此,但仍无法正常工作。

var _wasPageCleanedUp = false;
function logoutTimeUpdate()
{
    if (!_wasPageCleanedUp)
    {
        $.ajax({
            type: 'GET',
            async: false,
            url:baseUrl+"/Employee_control/logoutTimeUpdate",
            success: function ()
            {
                _wasPageCleanedUp = true;
                alert("hello");
            }
        });
    }
}
$(window).on("unload", function ()
{
    logoutTimeUpdate();
});

控制器

 public function logoutTimeUpdate(){
       $updatedLogoutTime=$this->Employee_model->logoutTimeUpdate();
        if ($updatedLogoutTime == 1) {
         $this->session->unset_userdata('login_session');
         $this->session->sess_destroy();
        } 
    }
}

型号

public function logoutTimeUpdate(){
  $data = array('logout_time' =>$this->current_date);
  $where = array('login_id'=>$this->session->userdata['login_session']['id']);

$this->db->where($where);
$this->db->update('tbl_current_login', $data); 
return 1;

}

1 个答案:

答案 0 :(得分:0)

您可以在卸载事件上编写代码。 例如。

<!DOCTYPE html>
<html>
    <head>
       <title></title>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>
       <div id="ProcessModel">

       </div>
        <script type="text/javascript">
          $(window).on('unload',function () {
                $.ajax({
                    type: 'GET',
                    async: false,
                    url: 'check.php?id=123'
                });
            });
        </script>
    </body>
</html>

这将在关闭标签页时调用。