本文章是利用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'; }