网站上有时可能会用到启动画面设置或其他如记住密码设置等等,需要再次刷新页面的时候不在显示或重新登录,这就需要cookie操作了,当然也可以使用localStorage 或 session。
cookie设置的话需要在 服务器环境上或火狐浏览器 才能看到效果。
设置cookie(永久):
document.cookie='name=张三';
多个设置(永久):
// 必须要一个一个的写:
document.cookie='name=张三';
document.cookie='age=24';
使用escape()加密码:
document.cookie='name='+escape('张三');
// 这时的name值为编码后的值 %u5F20%u4E09
然后使用unescape()进行解码识别:
console.log(unescape("%u5F20%u4E09")); // 张三
获取cookie(因为页面cookie 同 服务器语言php cookie设置不同,所以获取也不同,这里获取cookie值,需要js的字符串操作):
截取字符串方法:
substr(start, length);
substring(start, end);
获取cookie:
字符串转换为数组split(‘分隔符’);
// 打印所有的cookie 分号分隔
console.log(document.cookie); // name=张三 (返回值类型是字符串类型)
// 可以把字符串拆分成数组,然后再操作
console.log(document.cookie.split(';')); // ["once=true", " age=24"]
设置过期时间:
var date = new Date();
date.setDate(date.getDate()+31); // 设置31天后过期
document.cookie = "name=zhangsan;expires="+date;
删除cookie:
var date = new Date();
date.setTime(date.getTime()-10000); // 把时间设为当前时间以前
document.cookie = "name=zhangsan;expires="+date.toGMTString(); // 重新对上面设置的cookie重设置,这样cookie就删除掉了
设置及删除不同路径下的cookie
设置:
var date = new Date();
date.setDate(date.getDate()+31); // 设置31天后过
document.cookie="game=lol;expires="+date+";path=/"; // 根路径下的
var date = new Date();
date.setDate(date.getDate()+31); // 设置31天后过
document.cookie="game=lol;expires="+date+";path='/test/'"; // 根目录下的test目录
删除(这个与上面一样):
var date = new Date();
date.setTime(date.getTime()-10000); // 把时间设为当前时间以前
document.cookie = "game=lol;expires="+date.toGMTString()+"path='/test/'";
欢迎关注技术开发分享录:http://fenxianglu.cn/