做開發時,很多人會直接把 Discuz 的 common.js 裡那組 getcookie/setcookie 拿來用。我自己就吃了虧:本機測得好好的,換到 IE 實測卻完全讀不到值。同事給了這個 jquery.cookie.js,程式碼很短,值得逐段讀過一次。
$.cookie('the_cookie'); // 讀取
$.cookie('the_cookie', 'the_value'); // 寫入(工作階段 cookie)
$.cookie('the_cookie', 'the_value', { expires: 7 }); // 寫入,7 天後過期
$.cookie('the_cookie', 'the_value', {
expires: 7, path: '/', domain: 'jquery.com', secure: true
}); // 指定全部選項
$.cookie('the_cookie', null); // 刪除(值傳 null)
參數說明:expires 可以是天數整數或 Date 物件,傳負值或過去日期即為刪除;path 預設為建立它的頁面路徑;domain 預設為當前網域;secure 為 true 時要求以 HTTPS 傳輸。
jQuery.cookie = function (name, value, options) {
if (typeof value != 'undefined') {
// ---- 有傳值:設定 cookie ----
options = options || {};
if (value === null) {
value = '';
options.expires = -1; // 過期時間設為過去 → 刪除
}
var expires = '';
if (options.expires &&
(typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
// 用 expires 屬性,因為 max-age 不被 IE 支援
expires = '; expires=' + date.toUTCString();
}
var path = options.path ? '; path=' + options.path : '';
var domain = options.domain ? '; domain=' + options.domain : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value),
expires, path, domain, secure].join('');
} else {
// ---- 只傳名稱:讀取 cookie ----
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// 判斷這段是否以我們要的名稱開頭
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(
cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
expires 而非 max-age。 原始碼刻意註明這點,因為舊版 IE 不認 max-age,這正是它比某些「抄來就用」的版本可靠的地方。encodeURIComponent/decodeURIComponent。 少了編碼,值裡只要出現分號或空白就會把 cookie 打斷,中文也可能亂碼。name + '=' 而非單純 indexOf。 這樣才不會把 user_name 誤判成 user。這是很多自製 cookie 函式會犯的錯。寫入時若沒有指定 path,cookie 會預設綁在「當前頁面所在的路徑」上。於是同一個網域下,從 /a/page.aspx 寫入的 currentMenuID,在 /b/page.aspx 用同樣的名稱去讀就會讀不到——因為它們其實是兩個不同的 cookie。解法是寫入時一律明確指定 path:
$.cookie("currentMenuID", menuID, { path: "/" });
如此一來,同域底下同一個名稱就只會對應一個值,跨頁面讀寫才不會出現「明明設定了卻抓不到」的靈異現象。