cookie:存储内容小,存储在浏览器上的一小段数据,用来记录某些当页面关闭或者刷新后仍然需要记录的信息,在控制台用[document.cookie]查看你当前正在浏览的网站的cookie。cookie可以用js在浏览器直接设置,也可以在服务端通使用http协议规定set-cookie来让浏览器种下cookie
sessionStorage:存储内容大,关闭浏览器再打开缓存就没有了,存储浏览器的临时会话中
localStorage:存储内容大,不会因为关闭浏览器重启电脑消失,所以是存放在硬盘里面而不是内存
eg:
// cookie
// 获取cookie值
function testgetCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++){
var c = ca[i].trim();
if (c.indexOf(name)==0)
return unescape(c.substring(name.length,c.length));
}
return "";
}
// 设置cookie值
function testsetCookie(cname,cvalue){
document.cookie=cname+"="+escape(cvalue);
}
// 删除cookie键值对
function testdeleteCookie(cname){
document.cookie = cname+"=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
/*localStorage保存*/
var localStorage=window.localStorage;
if (localStorage) {
localStorage.setItem("ticketsCookieLat",$scope.lat);
localStorage.setItem("ticketsCookielng",$scope.lng);
} else {
Cookie.write("ticketsCookieLat");
Cookie.write("ticketsCookielng");
}
获取cookie
var localStorage=window.localStorage;
if (localStorage) {
var ticketsCookieLat=localStorage.getItem("ticketsCookieLat");
var ticketsCookielng=localStorage.getItem("ticketsCookielng");
} else {
var ticketsCookieLat = Cookie.read("ticketsCookieLat");
var ticketsCookielng = Cookie.read("ticketsCookielng");
}
localStorage使用:
存数据:
var obj={ session:result.body.session, userName:result.body.userName } localStorage.setItem('key', JSON.stringify(obj)) 取数据:
var ss=JSON.parse(localStorage.getItem('key')).session console.log(JSON.stringify(ss))
原创文章,作者:余 倩倩,如若转载,请注明出处:https://www.pmtemple.com/flyingfish/1098/