JavaScript

超轻量级php框架startmvc

jQuery基于ajax实现页面加载后检查用户登录状态的方法

更新时间:2020-04-22 02:35 作者:startmvc
本文实例讲述了jQuery基于ajax实现页面加载后检查用户登录状态的方法。分享给大家供大家

本文实例讲述了jQuery基于ajax实现页面加载后检查用户登录状态的方法。分享给大家供大家参考,具体如下:

拥有会员功能的网站,如果会员已经登录,那么要显示相应的登录状态,而且这种显示的需求是在网站的每个页面都有的(目前国内网站貌似都是这么做的,还没有见过其他形式的状态显示方式),这样,在打开一个新的页面时就要知道这个会员是否已经登录,需要判断登录的状态。

1、解决方案。

为了能够实现在每一个页面判断会员登录状态的功能,我采用了页面时通过ajax传递参数通过后端返回的登录状态结果进行判断,当然,这种方式实现的前提是登录状态在后端可以保持或者能够查询到并且不利用页面向后端发送特别参数。

2、代码部分。

(1)html部分


<div id="state_content"></div>

(2)jquery部分


jQuery(document).ready(function ()
{
 getUserData();
});
function getUserData()
{
 var Option =
 {
 url: encodeURI('/Handler/AuthAccounts.ashx?action=getloginstate'),
 type: "post",
 dataType: 'text',
 cache: false, //设置为 false 将不会从浏览器缓存中加载请求信息。
 async: true, //(默认: true),所有请求均为异步请求。发送同步请求,请将此选项设置为 false。同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
 timeout: 150000, //设置请求超时时间(毫秒)。此设置将覆盖全局设置。
 error: function ()
 {
 },
 success: function (data, textStatus)
 {
 if (data == null || data == undefined)
 {
 return false;
 }
 jsondata = eval('(' + data + ')');
 if (jsondata.state == "success")
 {
 var weburl = '<a class="username">欢迎你,' + jsondata.message.split('|')[1] + '</a><a class="go_out" onclick="ExitLoginState()">退出</a>';
 $("#state_content").html(weburl); //内容
 }
 else
 {
 var textList = '<a href="/Login/index.shtml" rel="external nofollow" rel="external nofollow" >【登录】</a><a href="/Register/index.shtml" rel="external nofollow" rel="external nofollow" >【注册】</a>';
 $("#state_content").html(textList); //内容
 }
 },
 beforeSend: function ()
 {
 }
 };
 jQuery.ajax(Option);
 return false;
}
function ExitLoginState()
{
 var Option =
 {
 url: encodeURI('/Handler/AuthAccounts.ashx?action=exitloginstate'),
 type: "post",
 dataType: 'text',
 cache: false, //设置为 false 将不会从浏览器缓存中加载请求信息。
 async: true, //(默认: true),所有请求均为异步请求。发送同步请求,请将此选项设置为 false。同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
 timeout: 150000, //设置请求超时时间(毫秒)。此设置将覆盖全局设置。
 error: function ()
 {
 },
 success: function (data, textStatus)
 {
 if (data == null || data == undefined)
 {
 return false;
 }
 jsondata = eval('(' + data + ')');
 if (jsondata.state == "success")
 {
 alert("已经退出");
 var textList = '<a href="/Login/index.shtml" rel="external nofollow" rel="external nofollow" >【登录】</a><a href="/Register/index.shtml" rel="external nofollow" rel="external nofollow" >【注册】</a>';
 $("#state_content").html(textList); //内容
 }
 },
 beforeSend: function ()
 {
 }
 };
 jQuery.ajax(Option);
 return false;
}