原生 document.cookie 只能操作字串,讀寫都頗麻煩。jQuery 的 cookie 外掛把這件事包成一行 API。
<html>
<head>
<title>JQuery-Cookie 插件</title>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
</head>
<body>
<a href="#">設置 cookie1</a><br>
<a href="#">設置 cookie2</a><br>
<a href="#">獲取 cookie</a><br>
<a href="#">刪除 cookie</a><br>
</body>
</html>
<script type="text/javascript">
$(function() {
var COOKIE_NAME = 'test_cookie';
// 以「天數」設定過期
$('a').eq(0).click(function() {
$.cookie(COOKIE_NAME, 'test', { path: '/', expires: 1 });
return false;
});
// 以明確日期設定過期
$('a').eq(1).click(function() {
var date = new Date();
date.setTime(date.getTime() + (1 * 24 * 60 * 60 * 1000));
$.cookie(COOKIE_NAME, 'test', { path: '/', expires: date });
return false;
});
// 讀取
$('a').eq(2).click(function() {
alert($.cookie(COOKIE_NAME));
return false;
});
// 刪除(把值設為 null)
$('a').eq(3).click(function() {
$.cookie(COOKIE_NAME, null, { path: '/' });
return false;
});
});
</script>
整個外掛只有一個函式,透過「有沒有傳 value」來區分寫入與讀取:
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') {
// 有 value:寫入 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 = '; 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 {
// 沒傳 value:讀取 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;
}
};
/,就會刪不掉——這是最常見的「cookie 刪除失敗」原因。secure 與 HttpOnly(後者需由伺服器設定)。