什么是Cookie
概念:
Cookie实际上是一小段的文本信息。客户端请求服务器,如果服务器需要记录该用户状态,就使用response向客户端浏览器颁发一个Cookie。客户端浏览器会把Cookie保存起来。当浏览器再请求该网站时,浏览器把请求的网址连同该Cookie一同提交给服务器。服务器检查该Cookie,以此来辨认用户状态。服务器还可以根据需要修改Cookie的内容。
作用:
1.cookie会话跟踪技术:会话级别的cookie,当会话关闭时,cookie也就没有了
会话session:一个webApp由打开到全部关闭的过程
2.长生命周期的cookie,N天免登陆
JS设置cookie:
假设在A页面中要保存变量username的值("jack")到cookie中,key值为name,则相应的JS代码为:
document.cookie="name=zhangsan"
document.cookie = "pwd=123456";
长生命周期写:
document.cookie = "键=值;expires=标准日期对象";
let date = new Date();
date.setDate(date.getDate()+10);
document.cookie = "name=laowang;expires="+date;
document.cookie = "pwd=666;expires="+date;
JS读取cookie:
读(会话和长生命周期一样)
假设cookie中存储的内容为:name=jack;password=123
则在B页面中获取变量username的值的JS代码如下:
//cookie的读
//name=dazhangwei; pwd=123456
//解析以上字符串,将name和pwd的value打印出来
//由分号空格隔开的键值对字符串
//console.log(document.cookie);
// 注意事项:cookie的使用必须有服务器
let strCookie = document.cookie;
//"name=dazhangwei; pwd=123456"->["name=dazhangwei","pwd=123456"]
let arrCookie = strCookie.split("; ");
arrCookie.forEach((element)=>{
//"name=dazhangwei"->["name","dazhangwei"]
let arrItem = element.split("=");
console.log(arrItem[0],arrItem[1]);
});
JS删除cookie:
cookie没有直接删除的api,只能间接删除
a.将key对应的value设置为''
b.将expires设置为-1
cookie的删除只针对于长生命周期
document.cookie="name='';expires=-1";
cookie的封装
//读
function getCookie(key){
let strCookie = document.cookie;
let arrCookie = strCookie.split("; ");
for(let i=0; i<arrCookie.length; i++){
let item = arrCookie[i].split("=");
if(item[0] == key){
return item[1];
}
}
return '';
}
let value = getCookie("name");
console.log(value);
//增
function setCookie(key,value,day){
//会话级别
if(day == undefined){
document.cookie = `${key}=${value}`;
}else{
//长生命周期
let date = new Date();
date.setDate(date.getDate()+day);
document.cookie = `${key}=${value};expires=${date}`;
}
}
setCookie("id","9527");//会话级别
setCookie("name","laowang",7);//长生命周期
//删
function deleteCookie(key){
setCookie(key,'',-1);
}
deleteCookie("name");
案例:七天免登录
//cookie已存在
if(getCookie("name") != '' && getCookie("pwd") != ''){
location.href = "2.ok.html";
}else{
let oInputs = document.getElementsByTagName("input");
let oSelect = document.querySelector("select");
let oBtn = document.querySelector("button");
oBtn.onclick = function(){
switch(oSelect.value){
case "0":
setCookie("name",oInputs[0].value);
setCookie("pwd",oInputs[1].value);
break;
case "7":
case "30":
setCookie("name",oInputs[0].value,oSelect.value/1);
setCookie("pwd",oInputs[1].value,oSelect.value/1);
break;
}
location.href = "2.ok.html";
}
}
标签:25,name,value,pwd,let,cookie,document
From: https://www.cnblogs.com/qianfanqf/p/16969924.html