什么是 cookie ?
cookie 是有服务器生成,发送给浏览器(User-Agent),让浏览器设置一个 cookie,格式是以 键:值,成对展示,浏览器会将键值对(cookie),保存到某个目录下面,下次请求同意网站是就会把 键值对 发回给服务器(前提是浏览器设置了启用 cookie)
cookie 就是一个小型文件(浏览器一般对 cookie 内存大小有限制,通常为 4096k( 4kb ),一般用来记录一些占存叫很小,不太隐私的信息。
cookie 在本地,可以本地更改文件,敏感数据不要放在 cookie 里
cookie 是具有保质期
为什么需要 cookie ?
因为 HTTP 协议是无状态的,对于一个浏览器发出的多次请求,WEB 服务器是无法区分是不是来自同一个浏览器,所以需要额外的数据来维持会话,cookie 就是随着 HTTP 请求被传递的额外的数据。
cookie 的特点
设置/查看 cookie
document.cookie = "键=值"; // document.cookie 会获取所有 cookie ,无法单独获取某个 cookie
console.log( document.cookie );特点:在 cookie 中,同一个键只能存在一个值
document.cookie = "name=aaa";
console.log( document.cookie ); // "name=aaa"
document.cookie = "name=bbb";
console.log( document.cookie ); // "name=bbb"
默认 cookie 是暂时存在的(它们存储的值只在浏览器会话期间存在,用户退出浏览器,存储的值也会消失,如果想延长存在时间,就需要使用 exprices 添加一个到期时间)
给 cookie 添加时间戳,需要使用 exprices
var myDate = new Date();
document.cookie = "name=aaa;exprices="+myDate;
max-age 也能达到延长存在时间的作用,但它设置的是时间段,单位是 s,但 max-age 返回的时间是格林时间,有时区影响
document.cookie = "name=aaa;max-age=10"; // 这个 cookie 存储的信息会在打开页面的 10 秒后过期(删除)删除 cookie
exprices --> 设置一个历史时间,当浏览器检查目标时间小于当前时间,就删除cookie
max-age --> 直接将时间段设置为 0,浏览器经过 0 秒之后,直接删除 cookie
自己封装一个操作 cookie 增/删/改/查 的函数
var operationCookie = {
// 增 / 改
set : function( key , val , date ){ // 增加 cookie
var oDate = new Date();
oDate.setDate( oDate.getDate() + parseInt(date) );
document.cookie = key + "=" + val + ";expires=" + oDate;
return this; // 实现链式调用
},
// 删
del : function( key ){
this.add( key , "" , -1 );
return this;
},
// 查
get : function( key , callback ){ // 1.需要查询的数据名,callback 是操作获取到的数据
var allCookie = document.cookie;
var cookieArr = allCookie.split("; ");
cookieArr.forEach(function(ele){
var item = ele.split("=");
if(item[0] == key ){
if( callback ){
callback( item[i] );
};
}
});
return this;
},
}