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就不存在了。