Storage是为了给浏览器增加记忆功能,方便在同一站点共享存储数据
cookie是早期在客户端的存储机制
Storage分为sessionStorage和localStorage(h5新添的)
各个存储都存在生命周期:
sessionStorage:打开浏览器到关闭浏览器
localStorage:永久化存储在本地硬盘
cookie:可以设置有效存储时间
‘同源策略’:
Storage通常是整个站点,最大为5M甚至更大
cookie是文件当前目录的所有文件及值文件,最大为4k,每次都要随http请求发送
Storage的用法:
dot方式来操作
1 localStorage.username = 'john';
2 localStorage.password = 12;
3 console.log(localStorage.username + ' ' +localStorage.password);
2 localStorage.password = 12;
3 console.log(localStorage.username + ' ' +localStorage.password);
setItem和getItem
1 localStorage.setItem('myName', 'whistle');
2 localStorage.setItem('password', 24);
3 console.log(localStorage.getItem('myName') + ' ' + localStorage.getItem('password'));
2 localStorage.setItem('password', 24);
3 console.log(localStorage.getItem('myName') + ' ' + localStorage.getItem('password'));
cookie的用法:
ps:这个Opera和chrome不能打印,所以换到Firefox
ps:试了半天,只能存一个,存多个还是拼接字符串吧
1 document.cookie="age=28;expire="+(new Date()).toGMTString()+10;
2 console.log(document.cookie);
3 var allCookie = document.cookie.split(';');
4 console.log(allCookie);
2 console.log(document.cookie);
3 var allCookie = document.cookie.split(';');
4 console.log(allCookie);