js中cookie的使用
COOKIE
- 每一个 HTTP 请求都会在请求头中携带 cookie 到服务端
- 每一个 HTTP 响应都会在响应头中携带 cookie 到客户端
- 也就是说,cookie 是不需要我们手动设置,就会自动在 客户端 和 服务端之间游走的数据
-
-
每一个
key=value是一条数据 -
多个数据之间以
;
// cookie 的形态 'a=100; b=200; c=300;'
-
-
数量有限制,一般是 50 条左右
-
有时效性,也就是有过期时间,一般是 会话级别(也就是浏览器关闭就过期了)
-
const cookie = document.cookie console.log(cookie) // 就能得到当前 cookie 的值
// 设置一个时效性为会话级别的 cookie document.cookie = 'a=100' // 设置一个有过期时间的 cookie document.cookie = 'b=200;expires=Thu, 18 Dec 2043 12:00:00 GMT";' // 上面这个 cookie 数据会在 2043 年 12 月 18 日 12 点以后过期,过期后会自动消失
// 因为 cookie 不能直接删除 // 所以我们只能把某一条 cookie 的过期时间设置成当前时间之前 // 那么浏览器就会自动删除 cookie document.cookie = 'b=200;expires=Thu, 18 Dec 2018 12:00:00 GMT";'
<script>
//判断是不是对象
function isObject(data){
// 判定数据类型必须是object , date不能为空(因为typeof null === "object")
//data.constructor 区分数组和对象
return (typeof data === "object" && data !== null && data.constructor && data.constructor === Object)
}
//对象合并
function assign(){
var target = arguments[0]
for(var i = 1 ; i < arguments[i] ; i++){
for(var attr in arguments[i]){
target[attr] = arguments[i][attr]
}
}
return target
}
//删除cookie
function removeCookie( name , options ){
cookie( name ,"" , isObject( options ) ? assign( options , { expires : -1 }) : { path : options, expires : -1 })
}
//设置cookie和读取cookie
function setCookie(name , value , options){
// 让option不传参数的时候也是一个对象
if(arguments.length > 1 && typeof value === "string"){
if(!isObject(options)){
options = {};
}
if(typeof options.expires === "number"){
var d = new Date();
d.setDate(d.getDate() + options.expires)
}
return (
document.cookie = [
name + "=" + value,
typeof options.domain === "string" ? ";domain=" + options.domain : "",
typeof options.path === "string" ? ";path=" + options.path : "",
typeof options.expires === "number" ? ";expires=" + options.expires : ""
].join("")
)
}
var cookie_string = document.cookie;
var cookie_array = cookie_string.split("; ");
for(var i = 0 ; i < cookie_array.length ; i ++){
if( cookie_array[i].split("=")[0] === name ){
return cookie_array[i].split("=")[1]
}
}
return "";
}
cookie("test","hello",{
expires : 5
})
var res = cookie("test");
console.log(res);
</script>

浙公网安备 33010602011771号