一、Cookie
1、cookie_utils.js工具类
var operator = "=";
function getCookieValue(keyStr){
var value = null;
var s = window.document.cookie;
var arr = s.split("; ");
for(var i=0; i<arr.length; i++){
var str = arr[i];
var k = str.split(operator)[0];
var v = str.split(operator)[1];
if(k == keyStr){
value = v;
break;
}
}
return value;
}
function setCookieValue(key,value){
document.cookie = key+operator+value;
}
2、A页面 设置Cookie
setCookieValue("username",userInfo.username);
setCookieValue("userimg",userInfo.userImg);
3、B页面 在Cookie里取值
var name = getCookieValue("username");
var img = getCookieValue("userimg");
二、localstorage
1、A页面 设置localstorage
localStorage.setItem("user",JSON.stringify(userInfo));
2、B页面?在localstorage里取值
var jsonStr = localStorage.getItem("user");
var userInfo = eval("(" + jsonStr + ")");
localStorage.removeItem("user");
三、两者的区别
1、存储大小不一样
单个cookie保存的数据不能超过4kb,localstorage一般为5M
2、与服务器通信
cookie不但能在前端页面之间传值,还能在前后端之间传值
localStorage只能在前端页面之间传值
3、操作难易性
cookie需要自己封装setCookie和getCookie,localStorage可以用源生接口
|