1,什么是coolie
http的每一次请求之间是没有联系的。也就是说,你对同一个网页请求两次,这两次之间没有联系,因为每一次请求都会有三次握手四次挥手的过程,所以http协议是一种无状态协议,意思是说不能保持访问的状态。
但在很多时候,保留访问状态是必须要有的一种操作,比如:在首页登陆后,希望在别的页面能保持这种登陆的状态。所以,出现了一个技术,叫做会话技术。会话中首先有了cookie。
2,cookie操作
1,设置语法:
document.cookie = '键=值;expires=失效时间;path=能使用当前cookie的路径';
2,获取cookie:
var cookie = document.cookie;
console.log(cookie); // name=zhangsan; age=30
3,修改cookie,就是重新设置。
4,删除cookie,就是将失效时间设置为当前时间以前。
var date = new Date();
date.setTiem(date.getTime()-1000*60*60*8-1); // 当前时间的上一秒
document.cookie = 'name=zhangsan;expires='+date;
3,封装cookie
//添加或修改cookie
function setCookie(key,value,time1=null,path=null){
//判断time1是否有值
if(time1){
//设置存储时间
var dt = new Date(new Date()-8*3600*1000+time1*1000)
document.cookie=`${key}=${value};path=${path};expires=${dt}`
}else{
//设置cookie
document.cookie=`${key}=${value};path=${path}`
}
}
//封装获取cookie
function getCookie(key){
//获取所有cookie
var str = document.cookie
//分割当前字符串
var ar1=str.split("; ")
//遍历数组中每个元素
for(var i=0;i<ar1.length;i++){
//对当前遍历出来的字符串继续进行分割
var ar2=ar1[i].split("=")
//判断当前分割出来的键名是否等于传入的键名
if(ar2[0]==key){
return ar2[1]
}
}
}
//封装删除cookie
function delCookie(key){
setCookie(key,'',-1)
}