本文章是利用jq 來做自動登錄,具體需求如下,在用戶點擊了保存密碼後,下一次訪問時跳過登錄頁面,直接進入首頁,具體是利用token 來做的,判斷token是否存在;
1. 首先做一箇中間頁(在登錄之前的一個頁面,專門做跳轉,相當於一個跳轉頁);
$(document).ready(function () { var token = $.cookie(health.cookie_key); if (token == undefined || token == false) { //判斷token是否存在,不存在跳到登錄頁 location.href = '/health/login.html'; } else { let url = $.formateUrl('backend/user/info'); //存在的話,獲取用戶信息(本項目需求) $.get(url, function (res) { if (res.code == 0) { let currentInfo = []; currentInfo.push({ avatar: res.content.user.avatar, name: res.content.user.name, }); $.cookie(health.cookie_orgid_key, res.content.user.orgid, {path: '/'}); $.cookie(health.cookie_user_key, JSON.stringify(currentInfo), {path: '/'}); let returnUrl = $.getQueryString('returnUrl'); if (returnUrl) { location.href = returnUrl; } else { location.href = '/health/index.html'; //完成之後跳到首頁 } } else { //如果token 過期,先清除相處的相關數據,在跳到登錄頁 $.destroy(); //清除數據,自定義的方法destroy() location.href = '/health/login.html'; } }); } });
2.登錄頁 ,如果點擊了記住密碼,則只需以下操作。(具體代碼再項目中有,這裏只表達相關意思)
//記住密碼 var cookieOptions = {}; cookieOptions.path = '/'; if (this.selected === 'true' || this.selected === true) { // 如果記住密碼 cookieOptions.expires = 7; // 在cookie 中保存7天 } $.cookie(health.cookie_key, res.content.user.access_token, cookieOptions);
3. 之後跳到登錄頁
let referrer = $.getQueryString('referrer'); if (referrer) { location.href = decodeURI(referrer); } else { location.href = health.homeUrl + 'health/index.html'; }