abstract:本文實例講述了jQuery基于ajax實現(xiàn)頁面加載后檢查用戶登錄狀態(tài)的方法。分享給大家供大家參考,具體如下:擁有會員功能的網(wǎng)站,如果會員已經(jīng)登錄,那么要顯示相應(yīng)的登錄狀態(tài),而且這種顯示的需求是在網(wǎng)站的每個頁面都有的(目前國內(nèi)網(wǎng)站貌似都是這么做的,還沒有見過其他形式的狀態(tài)顯示方式),這樣,在打開一個新的頁面時就要知道這個會員是否已經(jīng)登錄,需要判斷登錄的狀態(tài)。1、解決方案。為了能夠?qū)崿F(xiàn)在每一個頁面判斷
本文實例講述了jQuery基于ajax實現(xiàn)頁面加載后檢查用戶登錄狀態(tài)的方法。分享給大家供大家參考,具體如下:
擁有會員功能的網(wǎng)站,如果會員已經(jīng)登錄,那么要顯示相應(yīng)的登錄狀態(tài),而且這種顯示的需求是在網(wǎng)站的每個頁面都有的(目前國內(nèi)網(wǎng)站貌似都是這么做的,還沒有見過其他形式的狀態(tài)顯示方式),這樣,在打開一個新的頁面時就要知道這個會員是否已經(jīng)登錄,需要判斷登錄的狀態(tài)。
1、解決方案。
為了能夠?qū)崿F(xiàn)在每一個頁面判斷會員登錄狀態(tài)的功能,我采用了頁面時通過ajax傳遞參數(shù)通過后端返回的登錄狀態(tài)結(jié)果進(jìn)行判斷,當(dāng)然,這種方式實現(xiàn)的前提是登錄狀態(tài)在后端可以保持或者能夠查詢到并且不利用頁面向后端發(fā)送特別參數(shù)。
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, //設(shè)置為 false 將不會從瀏覽器緩存中加載請求信息。 async: true, //(默認(rèn): true),所有請求均為異步請求。發(fā)送同步請求,請將此選項設(shè)置為 false。同步請求將鎖住瀏覽器,用戶其它操作必須等待請求完成才可以執(zhí)行。 timeout: 150000, //設(shè)置請求超時時間(毫秒)。此設(shè)置將覆蓋全局設(shè)置。 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); //內(nèi)容 } 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); //內(nèi)容 } }, beforeSend: function () { } }; jQuery.ajax(Option); return false; } function ExitLoginState() { var Option = { url: encodeURI('/Handler/AuthAccounts.ashx?action=exitloginstate'), type: "post", dataType: 'text', cache: false, //設(shè)置為 false 將不會從瀏覽器緩存中加載請求信息。 async: true, //(默認(rèn): true),所有請求均為異步請求。發(fā)送同步請求,請將此選項設(shè)置為 false。同步請求將鎖住瀏覽器,用戶其它操作必須等待請求完成才可以執(zhí)行。 timeout: 150000, //設(shè)置請求超時時間(毫秒)。此設(shè)置將覆蓋全局設(shè)置。 error: function () { }, success: function (data, textStatus) { if (data == null || data == undefined) { return false; } jsondata = eval('(' + data + ')'); if (jsondata.state == "success") { alert("已經(jīng)退出"); 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); //內(nèi)容 } }, beforeSend: function () { } }; jQuery.ajax(Option); return false; }
更多關(guān)于jQuery基于ajax實現(xiàn)頁面加載后檢查用戶登錄狀態(tài)的方法請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!