代码页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>封装Cookie1</title>
<script>
window.onload=function(){
var CookieUtil={//所有名字和值都是经过URL编码的,所以必须使用encodeURIComponent来解码
set:function(name, value, expires, path, domain, secure){
//encodeURIComponent()函数可把字符串作为 URI 组件进行编码。
var cookieText= encodeURIComponent(name) + "=" + encodeURIComponent(value);
if(expires instanceof Date){
//toGMTString()方法可根据格林威治时间 (GMT) 把 Date 对象转换为字符串,并返回结果
cookieText += "; expires=" + expires.toGMTString();
}
if(path){
cookieText += "; path=" + path;
}
if(domain){
cookieText += "; domain=" + domain;
}
if(secure){
cookieText += "; secure";
}
document.cookie=cookieText;
},
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;
}
//decodeURIComponent() 函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
return cookieValue;
},
unset:function(name, path, domain, secure){
this.set(name, "", new Date(0), path, domain, secure);
}
}
//使用方法
CookieUtil.set("name","要桭不杯!");
CookieUtil.set("wen","诶就是人非");
//设置cookie,包括它的路径,域,失效日期(2010-01-01)
CookieUtil.set("name1","chen_wen_xian","/books/projs","www.baidu.com",new Date("January 1, 2010"));
alert(CookieUtil.get("name"));
//alert(document.cookie);
//var d = new Date()
//alert(d.toGMTString());
}
</script>
</head>
<body>
</body>
</html>
注意:要测试的,需要在火狐浏览器中测试;如果是用其他浏览器测试,需要把页面放在服务器环境下进行测试;
在火狐浏览器中点击右键-->查看页面信息-->安全-->查看Cookie