基本的cookie操作有三种:读取、写入、删除。
var CookieUtil = {
//根据cookie的name获取相应的value。它会在document.cookie字符串中查找cookie名加上等于号的位置。如果找到了
//就使用indexOf()查找该位置之后的第一个分号(表示了该cookie的结束位置)。如果没有找到分号,则表示该cookie
//是字符串中最后一个,则余下的字符串都是cookie的值。如果没有发现cookie,则返回null。
get:function(name){
var cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if(cookieStart > -1){
var cookieEnd = document.cookie.indexOf(";",cookieStart);
if(cookieEnd == -1){
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));
}
return cookieValue;
}, set:function(name,value,expires,path,domain,secure){
//name和value需要使用URL编码。
var cookieText = encodeURIComponent(name) + "=" +encodeURIComponent(value);
if(expires instanceof Date){
cookieText += "; expires=" + expires.toGMTString();
}
if(path){
cookieText += "; path=" + path;
}
if(domain){
cookieText += "; domain=" + domain;
}
if(secure){
cookieText += "; secure";
}
document.cookie = cookieText;
},
//删除已有的cookie的间接方法。new Date(0)设置失效时间为1970-01-01.这样就能确保删除cookie。
unset:function(name,path,domain,secure){
this.set(name,"",new Date(0),path,domain,secure);
}
}; //设置cookie
CookieUtil.set("name","Nicholas");
CookieUtil.set("book","professional Javascript"); //读取cookie的值
alert(CookieUtil.get("name")); //"Nicholas"
alert(CookieUtil.get("book")); //"professional Javascript" //删除cookie
CookieUtil.unset("name");