【问题标题】:Update logout time in the database once close the tab关闭选项卡后更新数据库中的注销时间
【发布时间】:2019-07-27 17:37:27
【问题描述】:

我的问题是当用户关闭选项卡时,我必须调用 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;

}

【问题讨论】:

  • 像这样向窗口对象添加一个事件 - stackoverflow.com/a/19538231/9332875
  • @kenzotenma,那么我必须在我的问题中使用哪个代码?以及如何使用链接中的答案调用 ajax?
  • $(window).on 替换为我分享的那个,并将logoutTimeUpdate(); 放在两者之间。
  • 我猜你的问题 $(window).on 没有工作,因为它没有返回任何东西。出于某种原因,beforeunloadunload 等事件的回调需要返回一些东西,不知道为什么。
  • @kenzotenma,我检查了这个 URL stackoverflow.com/questions/4945932/…。我试过了,但没有为我工作。

标签: php jquery mysql ajax codeigniter-3


【解决方案1】:

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

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

这将在关闭选项卡时调用。

【讨论】:

  • 你能分享这个例子吗?因为我 itred unload, onbeforeunload 但两者都不适合我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 2017-12-08
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 2015-05-29
  • 2014-10-12
相关资源
最近更新 更多