检测用户是否通过JS使用php注销(没有会话),如果是,则停止执行JS函数的其余部分

Detecting if a user has logged out (got no session) using php via JS, and if so - stopping the execution of the remainder of the JS function

本文关键字:JS 如果 函数 余部 执行 会话 使用 是否 用户 php 注销      更新时间:2023-09-26

我正在尝试找到一种方法来检测用户在运行特定的JS/jQuery函数时是否没有会话(这可以通过两种方式发生——会话是否过期,或者用户是否在另一个浏览器窗口/选项卡中注销)。如果用户没有会话,则函数应在此时停止执行(返回false)。

我试过这样使用AJAX:

function CheckForSession() {
        var str="chksession=true";
        jQuery.ajax({
                type: "POST",
                url: "chk_session.php",
                data: str,
                cache: false,
                success: function(res){
                    if(res == "0") {
                      alert('Your session has been expired!');
                    }
                }
        });
}

chk_session.php是

  require('includes/application_top.php');

  $session_test = $_SESSION['customer_id'];
  if($session_test == '') {
    //session expired
      echo "0";
    } else {
    //session not expired
    echo "1";
   }

然后我在里面调用这个函数:

jQuery('body').on('click','.cart_icon_div1.active.selected', function(){
        CheckForSession();
    //if the session doesn't exist, stop running this function, else continue to do more cool stuff
    });

问题是我无法让它发挥作用。坦率地说,我的js/jQuery技能非常有限。

非常感谢您的帮助。

这里有一个回调版本:

function CheckForSession(onLoggedIn, onLoginExpired) {
    var str="chksession=true";
    jQuery.ajax({
            type: "POST",
            url: "chk_session.php",
            data: str,
            cache: false,
            success: function(res){
                if(res == "0") {
                    onLoginExpired();
                } else {
                    onLoggedIn();
                }
            }
        });
}

jQuery('body').on('click','.cart_icon_div1.active.selected', function(){
    CheckForSession(function() {
        // Do any important session-required stuff here
       }, 
       function() { 
        alert('Your session has been expired!');
    });
});

您可以做的几件事:

  • 在页面加载时检查登录状态,并在用户单击时准备就绪
  • 将回调传递到CheckForSession中,当服务器发出响应时,CheckForSession会运行

就我个人而言,我会选择选项1。