简体   繁体   English

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

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

I have one index.php which requires session. 我有一个index.php需要会话。 Also I have sessioncheckpage.php 我也有sessioncheckpage.php

which look like code below. 看起来像下面的代码。 It works well. 它运作良好。

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

But how can I reload index.php? 但是如何重新加载index.php? My Javascript code just would to refresh sessioncheckpage.php in the background. 我的Javascript代码只是在后台刷新sessioncheckpage.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>

Above is jQuery which is included in index.php. 上面是jQuery,它包含在index.php中。 Also it would be possible to reload index.php as a sessioncheckpage.php but there is video content so video should not stop after page refresh (session checking).... 也可以将index.php重新加载为sessioncheckpage.php,但是有视频内容,所以视频不应该在页面刷新(会话检查)后停止....

You can check the status code 您可以查看状态代码

PHP Code PHP代码

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

jQuery 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");
        }
    }
}); 

If your sessionchecker script is RESTful (ie implements HTTP error codes), then add to your $.ajax call an error function. 如果您的sessionchecker脚本是RESTful(即实现HTTP错误代码),则将$.ajax调用添加到错误函数中。 Otherwise, add a clause in your success function to call window.location.reload() 否则,在success函数中添加一个子句来调用window.location.reload()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM