如何使用 JavaScript 检查 Session 是否过期 [英] How to check if the Session expires using JavaScript

查看:79
本文介绍了如何使用 JavaScript 检查 Session 是否过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一旦会话过期,我想将用户从应用程序中的任何位置重定向到登录页面".

I want to redirect the user to the "Login page" from anywhere in the application once the session is expired.

我如何使用 JavaScript 实现这一点?

How can I accomplish that using JavaScript?

推荐答案

会话的典型实现需要两件事:

A typical implementation of a session requires two things:

  1. 浏览器中的 cookie
  2. 与存储在 cookie 中的号码相关联的会话的服务器端记录

这些 cookie 通常设置为会话 cookie.它们在浏览器关闭时过期.因此,您无需担心测试它们来实现这一目标.

These cookies are usually set up as session cookies. They expire when the browser closes. Thus you don't need to worry about testing them to achieve this.

要确定会话在服务器上是否仍然有效,您需要(定期)向服务器发出 HTTP 请求(您可以使用 Ajax 执行此操作)并让服务器以有关会话生命周期的信息进行响应.

To find out if the session is still valid on the server, you need to (periodically) make an HTTP request to the server (you can do this with Ajax) and have the server respond with information about the life of the session.

一个简单的解决方案是返回真或假,然后重定向(通过设置location.href)如果它是假的.

A simple solution would be to return true or false, and then redirect (by setting location.href) if it is false.

更有效的解决方案是返回会话的剩余生存时间,并使用该信息确定下次检查的时间(如果为 0,则重定向).更多

A more efficient solution would be to return the remaining time to live for the session, and use that information to determine when next to check (and redirect if it is 0). A more

这篇关于如何使用 JavaScript 检查 Session 是否过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆