项目描述
上传时间
浏览人数
大家好,今天我做了一个Cookie-登录
首先先连接一个jquery包
在连接一个Cookies.js包
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=/"; } }
然后,在首页html部分写两个相同结构的div
<div class="container d-flex"> <div class="contact-info mr-auto no-login"> <a href="dl.html">登录/免费注册</a> <i class="icofont-phone"></i> +1234 5678 </div> <div class="contact-info mr-auto is-login"> <a href="blog.html">欢迎您,<span></span></a> <i class="icofont-phone"></i> +1234 5678 </div> </div>
把 class为icofont-phone先隐藏
<style type="text/css"> .is-login { display: none; } </style>
在登录页面写写输入框
<form> <input type="text" id="email" placeholder="账号/手机号/邮箱"class="a"> <input type="text" id="password" placeholder="密码"class="a"><br> <button type="button" onclick="login()" class="b">登录</button> <button style="color: red"class="b"><a href="zc.html"style="color: white" >注册</a></button> </form>
js部分
<script type="text/javascript"> $(function () { let ulc=getCookie("USER_LOGIN_CACHE") if(ulc){ window.location.href="index.html" } }) function login() { let un = $("#email").val(); let pw = $("#password").val(); if (un && pw) { let url = "http://47.97.212.173/user/login"; let params = { email: un, password: pw, }; $.ajax({ url: url, type: "post", data: params, dataType: "json", success: function (result) { console.log(result); if (result.state == 1) { console.log(result.data); let datastr=JSON.stringify(result.data) console.log(datastr); setCookie("USER_LOGIN_CACHE",datastr,0.5) window.location.href = "blog.html" } else { alert("登陆失败," + result.msg) } }, error: function (err) { alert("发生未知错误,请联系站点管理员!") } }) } else { alert("请正确填写email和password") } } </script>
让class为on-login的隐藏,class为is-login的显示出来
$(function () { let ulc = getCookie("USER_LOGIN_CACHE"); if (ulc) { console.log("当前登录人:"); console.log(ulc); ulc = JSON.parse(ulc); $(".is-login>a>span").text(ulc.nickname) $(".no-login").hide() $(".is-login").show() } else { console.log("没人登录"); } })
登录前首页页面
登录页页面
登录后首页页面
登录后点击昵称进入个人页面