在浏览器端保存一些数据的好处是,当再次访问该页面时,就不需要向服务器请求。可以从浏览器端直接读取。
1.cookie
cookie的特点是会随着HTTP请求头信息一起发送,能存储的数据容量有限,不同浏览器cookie大小不一样,一般为
4kb,而IE6大约只有2K。
cookie
的常用三种方法
(
1
)
设置
cookie
function setcookie(name,value){
var date = new Date();
date.setDate(date.getDate()+1);
document.cookie= name + "=" + escape(value) +
";expire="+ date.toGMTString();
console.log(document.cookie);
}
setcookie("wenhao","shuaige");
(
2
)
读取
cookie
function readcookie(name){
if(document.cookie){
var start = document.cookie.indexOf(name+"=");
if(start != -1)
var end = document.cookie.indexOf(";",start+name.length);
if(end != -1)
var str = document.cookie.substring(start+name.length+1,end);
console.log(str);
}
}
readcookie(“wenhao”);
(
3
)
删除
cookie
function delCookie(){
var data = new Date();
date.setTime(data.getTime()-1);
document.cookie= name + “=” + val + “;expire=” + date.toGMTString();
}
2.userData
userData只能在IE浏览器来存储数据,容量可以达到640K。
3.sessionStorage
临时存储,只支持一些高版本的浏览器(ie不支持),用这种方式存储的数据仅窗口级别有效,当新开窗口或者关闭页面时,原来的数据就失效了。
4.globalStorage
只支持高版本的浏览器,类似于IE的userData。
常用的操作globalStorage方法:
1.赋值
globalStorage[location.hostname]['name'] = '111';
2.读取
globalStorage[location.hostname]['name'];
globalStorage[location.hostname].removeItem('name');
5.Flash ShareObject
需要在页面中插入一个Flash插件(我没有用过,应该是需要引入外部文件),而且能够跨浏览器。
6.Google Gear
Google开发出的一种本地存储技术,需要安装Gear组件才能使用。
6.localStorage
localStorage是Web Storage互联网存储规范中的一部分,大部分浏览器都能支持。