三种浏览器的缓存方法
cookie:
会话跟踪技术
特点:
1、存储有大小限制 4K
2、有时间限制 expires:
3、只能存放字符串
4、域的限制
//设置cookie
function setCookie (_name,val,day) {
var d = new Date();
d.setDate(d.getDate()+day);
document.cookie = _name+"="+val+";path=/;expires="+d;
}
setCookie ("username","zhao",10)
//删除cookie
function removeCookie(_name,val){
setCookie ("username","zhao",-1)
}
removeCookie("username","zhao");
//获取所有cookie
function getCookie(_name){
var cookie = document.cookie;
//将字符串转换为数组
var arr = cookie.split("; ")
//遍历二次分割成熟
for(var i=0;i<arr.length;i++){
//分割
var newArr = arr[i].split("=");
//判断如果传递进啦的name值等于 newArr[0]
if(_name == newArr[0]){
return newArr[1]
}
}
}
getCookie("username")
localstorage:
大小限制:5M
时间限制:永久存储
设置localstorage:
window.localstorage:
localstorage.name="李皮";
localstorage["name"] = "李皮";
localstorage.setItem(key,val);
获取localStorage:
localStorage.属性
localStorage["属性"];
localStorage.getItem(属性)
删除localStorage:
localStorage.clear();
localStorage.removeItem();
sessionStorage:
临时存储:当浏览器关闭的时候就销毁掉了
设置
sessionStorage.name="李皮"
sessionStorage["age"]=38
sessionStorage.setItem("sex", "双人")
获取
sessionStorage.getItem("age")
删除
sessionStorage.removeItem("age");
如何将json对象转换为字符串
JSON.stringify(对象);
返回值是一个字符串
如何将字符串转换为json对象
JSON.parse(字符串)
返回值是对象