了解cookie通信协议
Cookie 存储在本地终端的数据
cookie的封装与locastorage区别
1. 存储时间:cookie默认会话期有效 ,locastorage默认永久有效
2. 存储大小:cookie 4k ; locastorage 5M
3. 存储条数:cookie 170条左右; locastorage无限制
4. 操作形式:cookie麻烦
5. cookie默认会随着http请求发送服务器;
语法:(字符串)
1. 增
document.cookie = "username = yang ; expires="+oDate; oDate是时间变量。
为了保证cookie在存储和读取的过程中,防止中文乱码,一般情况下,将中文编码存储,读取时在解码读取。
document.cookie= 'user=' + encodeURLComponent('钢铁侠'); //讲中文编译成字符
console.log(decodeURLComponent(document.cookie)) //将对应字符解码成中文
2. 删
document.cookie = "username =; expires="+oDate //设置过期时间
3. 查
console.log(document.cookie) //查到所有cookie
常用可选项
expires: 过渡时间,必须写日期对象,系统会清除过期cookie
path: 限制访问路径 ,设置的路径和当前文件路径必须一致,否则访问失败
domain: 可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”。
封装
// 增
functionsetCookie(key, value, n) {
varoDate=newDate();
oDate.setDate(oDate.getDate() +n);
document.cookie=key+"="+value+"; expires"+oDate;
}
// 删
functionremoveCookie(key){
setCookie(key, 1,-1)
}
// 查
functiongetCookie(key) {
varstr=document.cookie;
vararr=str.split("; ")
for (vari=0; i<arr.length; i++) {
vararr1=arr[i].split("=");
if (arr1[0] ==key) {
returnarr1[1];
}
}
}