显示会话过期消息


Show session expired message

我希望我的页面在会话过期时显示警报。我已经搜索了堆栈并找到了带有 JQuery 的 MVC:处理会话过期

这个很棒的链接解释了如何保留会话。但问题是它使用计时器。在我的情况下,用户可能会将其系统保持在睡眠模式,使网页保持打开状态。在这种情况下,计时器停止工作。请求为我建议一种方法,以便我的代码即使系统进入睡眠模式然后唤醒,也会知道会话已过期。

让这样的东西在所有浏览器和所有平台上工作的唯一方法是通过轮询。你可以使用一个JavaScript setInterval,它每隔一段时间就会调用一次ajax。如果将间隔设置为低于服务器超时的时间,则续订会话,并且不会过期。如果您将其置于服务器超时时间之上,那么您将知道它是否真的过期并告诉客户端它确实过期了。

将会话 cookie 从 php 存储到浏览器以设置会话结束信息是很常见的。 在服务器端,过期信息存储在数据库中。在每个用户请求服务器上,服务器都会更新cookie和数据库。使用 jquery cookie 插件,您可以检查会话何时过期。您可以使用轮询(而不是池化(来做到这一点,就像其他人建议的那样,将计时器事件设置为会话过期的时间。

编辑

我有一个类似的应用程序正在开发。这是我所做的:在 PHP 中,在每个 Ajax 请求中,我都设置了 cookie

$exp_gmt = gmdate("D, d M Y H:i:s", time() + $this->allowcache_expire * 60)." GMT";
header("Expires: ".$exp_gmt);
header("Cache-Control: max-age=".$this->allowcache_expire * 60, false);

然后我在客户端使用这个jquery插件(对不起,我不记得在哪里找到它(

jQuery.cookie = function(d, e, b) {
    if(arguments.length > 1 && String(e) !== "[object Object]") {
        b = jQuery.extend({}, b);
        if(e === null || e === undefined) {
            b.expires = -1
        }
        if( typeof b.expires === "number") {
            var g = b.expires, c = b.expires = new Date();
            c.setSeconds(c.getSeconds() + g)
        }
        e = String(e);
        return (document.cookie = [encodeURIComponent(d), "=", b.raw ? e : encodeURIComponent(e), b.expires ? "; expires=" + b.expires.toUTCString() : "", b.path ? "; path=" + b.path : "", b.domain ? "; domain=" + b.domain : "", b.secure ? "; secure" : ""].join(""))
    }
    b = e || {};
    var a, f = b.raw ? function(h) {
        return h
    } : decodeURIComponent;
    return ( a = new RegExp("(?:^|; )" + encodeURIComponent(d) + "=([^;]*)").exec(document.cookie)) ? f(a[1]) : null
}; 

我在页面上还有一个时钟:

showTime : function() {
    var today = new Date();
    var curr_date = today.getDate();
    var curr_month = today.getMonth() + 1;
    var curr_year = today.getFullYear();
    var curr_hour = today.getHours();
    var curr_min = today.getMinutes();
    var curr_sec = today.getSeconds();
    if(curr_date < 10)
        curr_date = '0' + curr_date;
    if(curr_month < 10)
        curr_month = '0' + curr_month;
    if(curr_hour < 10)
        curr_hour = '0' + curr_hour;
    if(curr_min < 10)
        curr_min = '0' + curr_min;
    if(curr_sec < 10)
        curr_sec = '0' + curr_sec;
    var curr_full = curr_date + "/" + curr_month + "/" + curr_year + "<br />" + curr_hour + ":" + curr_min + ' <span style="font-size:0.8em">' + curr_sec + '</span>';
    $('#clock').html(curr_full);
    setTimeout("showTime()", 1000);
}

在时钟功能结束时,您可以读取cookie并将其与当前时间进行比较,以查看它是否已过期。