JavaScript: 设置Cookie
JavaScript Cookie是一种适合客户端的、便利的持久性的数据存储方案。Cookie是一个名值对的列表,每个名值对以分号(;)隔开。下面介绍3个可重用的Cookie方法:
function writeCookie(name, value, days) {
// By default, there is no expiration so the cookie is temporary
var expires = "";
// Specifying a number of days makes the cookie persistent
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
// Set the cookie to the name, value, and expiration date
document.cookie = name + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
// Find the specified cookie and return its value
var searchName = name + "=";
var cookies = document.cookie.split(';');
for(var i=0; i < cookies.length; i++) {
var c = cookies[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(searchName) == 0)
return unescape(c.substring(searchName.length, c.length));
}
return null;
}
function eraseCookie(name) {
// Erase the specified cookie
writeCookie(name, "", -1);
}
一点点说明:
1. Cookie的名值不能使用分号(;)逗号(,)等号(=)以及空格,在name中容易保证这个规则,但是value很难保证,因此这里用escape函数进行编码,将value中的特殊字符用十六进制表示,如空格为"20%"。 同理读Cookie的值时,用unescape进行解码
2. 设置Cookie使用document.cookie="...",虽然cookie看上去像一个属性,但它和一般的属性不一样,改变它的赋值并不意味着丢失原来的值,而是新增加了一个Cookie.改变一个Cookie的赋值,只需要重新赋值即可。
示例:
writeCookie("username", "test");
writeCookie("password", "111");
这里创建了两个cookie:username和password,如果password发生改变,如变为"222",则writeCookie("password","222")将覆盖已有Cookie的值。
3. 删除Cookie,这里将Cookie的过期时间设置为前一天结束,因此该Cookie就不存在了。
浙公网安备 33010602011771号