如果使用 jquery 进行会话检查在后台失败,如何重定向索引.php页面


How to redirect index.php page if session checking with jquery fails in the background?

我有一个索引.php需要会话。我也有会话检查页面.php

看起来像下面的代码。效果很好。

$login_hash=$_SESSION['hash'];
if ($login_hash != $tulos) {
    session_destroy();
    header("Location: login.php");
}

但是如何重新加载索引.php?我的Javascript代码只是在后台刷新会话检查页面.php。

<script>
var interval    =   0;
function start(){
    setTimeout( function(){
        ajax_function();
        interval    =   10;
        setInterval( function(){
            ajax_function();
        }, interval * 1000);
    }, interval * 1000);    
}
function ajax_function(){
    $.ajax({
        url: "sessionchecker.php",
        context: document.body,
        success: function(result){
            $('.time').html(result);
        }
    }); 
}
$( window ).load(function(){
    var time    =   new Date();
    interval    =   10 - time.getSeconds();
    if(interval==10)
        interval    =   0;
    start();
});
</script>

以上是包含在index.php中的jQuery。也可以重新加载索引.php作为会话检查页面.php但有视频内容,因此视频不应在页面刷新(会话检查)后停止。

您可以检查状态代码

PHP代码

<?PHP 
if(notLoggedIN()){
    header("HTTP/1.1 401 Unauthorized");
    exit;
}
?>

jQuery

$.ajax({
    url: "sessionchecker.php",
    context: document.body,
    success: function(result){
        $('.time').html(result);
    }
    error: function(jqXHR, status, code){
        if (jqXHR.status === 401) {
           window.location.replace("/login.php");
        }
    }
}); 

如果您的会话检查器脚本是 RESTful (即实现 HTTP 错误代码),则添加到您的$.ajax调用错误函数。否则,请在成功函数中添加一个子句来调用window.location.reload()

$.ajax({
    url: "sessionchecker.php",
    context: document.body,
    success: function(result){
        $('.time').html(result);
    }
    error: function(jqXHR, status, error){
        window.location.reload();
    }
});