一、什么是cookie
首先咱们需要知道:
http协议:超文本传输协议,用于从web服务器传输超文本到本地浏览器的传输协议,他是一个无状态的协议,即他不能判别你的身份。
而cookie,就是缓存在客户端的一小串数据,向服务器发送请求时,客户端把cookie一同交给服务器,服务器依次来辨认用户状态。
二、封装cookie的三个基本操作
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cookie基础</title>
<script type="text/javascript">
window.onload=function()
{
function setCookie(name,value,day)
{
var oDate = new Date();
oDate.setDate(oDate.getDate()+day);
document.cookie=name+"="+value+";expires="+oDate;
}
setCookie("name1","zhuo",7);
setCookie("name2","han",7);
console.log(document.cookie);
function getCookie(name)
{
var str =document.cookie;
var arr=str.split("; ");
for (var i=0;i<arr.length;i++) {
var arr1=arr[i].split("=");
if(arr1[0]==name)
{
return arr1[1];
}
}
}
console.log(getCookie("name1"));
function removeCookie(name)
{
setCookie(name,1,-1);
}
removeCookie("name1");
removeCookie("name2");
console.log(getCookie("name1"));
}
</script>
</head>
<body>
</body>
</html>
三、cookie小应用-七天免登陆
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cookie应用</title>
<script src="../js/tool.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
window.onload=function()
{
var aInput=document.getElementsByTagName("input");
if(getCookie("username"))
{
aInput[0].value=getCookie("username");
aInput[1].value=getCookie("password");
}
aInput[3].onclick=function()
{
var username=aInput[0].value;
var password=aInput[1].value;
if(aInput[2].checked)
{
setCookie("username",username,7);
setCookie("password",password,7);
}
}
console.log(document.cookie);
}
</script>
</head>
<body>
账号:<input type="text" />
密码:<input type="password" />
<label><input type="checkbox" />七天免登陆</label>
<input type="button" name="" id="" value="登陆" />
</body>
</html>