项目描述
上传时间
浏览人数
一,首先安装一个cookie包
function setCookie(cName, cVal, expiresDays) { if (cName && cVal && expiresDays ){ cName = cName.replace(/\s+/g,''); cVal = cVal.trim(); if(cName && cVal){ let d = new Date(); d.setTime(d.getTime() + expiresDays * 24 * 60 * 60 * 1000); let gmtTimeStr = d.toUTCString(); document.cookie = cName+"="+cVal+"; expires="+gmtTimeStr+"; path=/"; } } } function getCookie(cName){ cName += "="; let cookiesArr = document.cookie.split(";"); for (let i = 0; i < cookiesArr.length; i++) { let item = cookiesArr[i].trim(); if(item.startsWith(cName)){ return item.substring(cName.length); } } return ""; } function removeCookie(cName){ cName = cName.trim(); if(cName){ document.cookie = cName+"=*; expires="+(new Date().toUTCString())+"; path=/"; } }
二,写一个登录页面
<form> <h1>会员登录</h1> <div class="field"> <input type="text" placeholder="用户名或邮箱" id="name" value="1487197804@qq.com"/> </div> <div class="field"> <input type="password" placeholder="密码" id="password" value="123456"/> </div> <div class="field"> <input type="button" value="登录" class="flat-btn" onclick="login()"/> </div> </form>
首页未登录界面展示
三,登陆成功状态获取cookie下的缓存信息
let str = JSON.stringify(result.data); setCookie("USER_LOGIN_CACHE",str,1); console.log(result.data)
四,已经登录状态下显示登陆者的信息
$(function () { let ulc = getCookie("USER_LOGIN_CACHE"); if(ulc){ ulc = JSON.parse(ulc); console.log(ulc); $(".popup-client>span").text(ulc.nickname); } });
已登录界面展示,登录按钮变为用户名称