梗概
实例
之一
document.cookie=""A=1"
document.cookie="B=2"新添加的cookie如下:"A=1;B=2;"
之一
前端设置cookie:
//1.设置本地的一个cookie数据--
//存储账号:
var name='lilei';
//过期时间--不能是中国时间
//有效期 需要是GMT时间toGMTString() / toUTCString() 请使用 toUTCString() 取而代之!!
var times=new Date();
//设置一个3分钟后过期 20*60*1000
var endTimes=new Date(times.getTime()+20*60*1000);
// document.cookie='uname='+name+';expires='+endTimes.toUTCString()+';path=/';
//2:---中文转码--------------------
var uname='aa22张三66';
//中文转码 encodeURIComponent(内容)
//3分钟过期 获取上面的时间
document.cookie='username='+encodeURIComponent(uname)+';expires='+endTimes.toUTCString()+';path=/';
document.cookie='password=123;expires='+endTimes.toUTCString()+';path=/';
//获取cookie
//语法:document.cookie
console.log(document.cookie);前端获取cookie
//假设:做登录
// if(document.cookie){
// //直接登录--获取账号和密码
// var name='';
// var mima='';
// // $.ajax({})
// }
//获取cookie----------------------
//方法1:字符串--转数组---
function getCookie(key){
//1.获取本地cookie字符串 字符串key=value;...
var cookies=document.cookie;
// console.log(cookies);
//2.字符串转数组
var arr=cookies.split(';');
// console.log(arr);//["username=aa22%E5%BC%A0%E4%B8%8966", " password=123"]
for(var i=0;i<arr.length;i++){
//arr[i] 数组每一项 每一项又是字符串 key=vlaue,key=value...
// console.log(arr[i]);//数组的每一项转数组 [key,value],[key,value],...
var newArr=arr[i].trim().split('=');
// console.log(newArr);//[username,aa22%E5%BC%A0%E4%B8%8966]
//3.获取参数key key==newArr[0] 输出newArr[1]
if(key==newArr[0]){
return decodeURIComponent(newArr[1]);//中文解码
}
}
}
var uname=getCookie('username');//返回给我username
console.log(uname);
var mima=getCookie('password');
console.log(mima);