HTTP协议:
HTTP:超文本传输协议,用于web服务器传输超文本到本地浏览器的传输协议,它是一个无状态的协议.
cookie:是指缓存在本地客户端的数据
不设置有效期 ;则关闭浏览器之后 cookie自动消失
cookie基本操作包括增,删,改,查
//设置cookie
var oDate=new Date();
oDate.setDate(oDate.getDate()+3);//设置cookie的有效期
document.cookie="username=wanglaowu;expires="+oDate;
//查询cookie
console.log(document.cookie);//name1=wanglaowu; name2=zhangsan; username=wanglaowu
//修改cookie (同名的cookie后面的覆盖前面的)
document.cookie="username=zhangsan";
document.cookie="username=zhangsan1";
console.log(document.cookie);//
//删除cookie
var oDate=new Date();
oDate.setDate(oDate.getDate()-1);//cookie过期就自动删除了
document.cookie="username=honny;expires="+oDate;
封装setCookie getCookie removeCookie方法
//封装设置cookie
function setCookie(name,value,day){
var oDate=new Date();
oDate.setDate(oDate.getDate()+day)
document.cookie=name+"="+value+";expires="+oDate;
}
//**读取指定name的cookie值**
function getCookie(name){
var str=document.cookie;
var arr=str.split("; ")
// console.log(arr)
for(var i=0;i<arr.length;i++){
var arr1=arr[i].split("=");
if(arr1[0]=name){
return arr1[1]
}
}
}
//封装清除cookie
function removeCookie(name){
setCookie(name,1,-1)
}
cookie的基础应用
实现7天免账号密码登录
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label for="user">用户名</label>
<input type="text" id="user">
<label for="pass">密码</label>
<input type="password" id="pass">
<label for="chexck">七天免登录</label>
<input type="checkbox" id="chexck">
<input type="button" value="登录">
<script>
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);
}
}
//封装设置cookie
function setCookie(name,value,day){
var oDate=new Date();
oDate.setDate(oDate.getDate()+day)
document.cookie=name+"="+value+";expires="+oDate;
}
//**读取指定name的cookie值**
function getCookie(name){
var str=document.cookie;
var arr=str.split("; ")
// console.log(arr)
for(var i=0;i<arr.length;i++){
var arr1=arr[i].split("=");
if(arr1[0]=name){
return arr1[1]
}
}
}
//封装清除cookie
function removeCookie(name){
setCookie(name,1,-1)
}
</script>
</body>
</html>