利用Cookie做一个简单的登录和注销
创建两个HTML文件------Login.html,Index.html
#Login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>登录页</title>
<script>
function check() {
var account = fm1.account.value;//获取账号值
var password = fm1.password.value;//获取密码
if (account == "") {
showMsg("请输入用户名");
}
else {
if (password == "") {
showMsg("请输入密码");
}
else {
if (account == "myname") {
if (password == "123") {
setCookie("username", account,30);//调用设置cookie的方法
window.location.href = "Index.html";//跳转
}
else {
showMsg("密码错误");
}
}
else {
showMsg("用户名错误");
}
}
}
}
//显示提示信息函数
function showMsg(msg) {
document.getElementById("Mesg").innerHTML = msg;
}
//设置cookie函数
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
</script>
</head>
<body>
<button type="button" onclick='showMsg("Tag")'>点击</button>
<div>请输入你的用户名和密码</div>
<form action="" name="fm1">
<input type="text" id="account" name="account" placeholder="输入账号">
<br />
<input type="password" id="password" name="password" placeholder="输入密码" />
<div>
<input type="button" value="登录" onclick="check()">
<input type="reset" value="重置">
</div>
</form>
<div id="Mesg"></div>
</body>
</html>
显示成功页面
#Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>首页</title>
<script>
//消除cookie的函数
function logout() {
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
location.reload();//刷新页面
}
//获取cookie的函数
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); }
}
return "";
}
//检测cookie函数
function checkCookie() {
var user = getCookie("username");//获取cookie
if (user.toString() == "") {
//若用户为空的事件
}
else {
document.getElementById("a1").remove();//删除id为a1的标签
document.getElementById("mine").innerHTML = user;//将用户插入到块里面
}
}
</script>
</head>
<body onload="checkCookie()">
<center><h1>INDEX</h1></center>
<div>
欢迎!
<text id="mine"></text>
<a id="a1" href="Login.html">请先登录</a>
<button type="button" onclick="logout()">注销</button>
</div>
</body>
</html>