[JQuery]
原本HTML要建立C、讀取R、刪除D、cookie我都使用別人寫的jquery 插件COOKIE plugin[1],使用上就簡化很多:
建立
$.cookie("example", "foo"); // Sample 1 $.cookie("example", "foo", { expires: 7 }); // Sample 2 $.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3
取得/刪除
alert( $.cookie("example") ); $.removeCookie("example");
缺點是這得架構在jquery,而且得引入一個插件,對於有時不想用jq的我造成困擾,的確jq是很方便啦,但是jq會一直升級有時只想單純的建立讀取,不想那一大包jq,所以使用javascript 的方法來解決。
[JavaScript]
// 建立cookie function createCookie(name, value, days, path) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + value + expires + "; path=/"; } //讀取 function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; } //刪除 function eraseCookie(name) { createCookie(name, "", -1); }
使用範例:
讀取
ds= readCookie('showadv');
建立(有效3日)
var ds="some value";
createCookie('showadv', ds, 3);
刪除(等於建立一個逾期的cookie)
eraseCookie('showadv');
參考資料
[1] http://stackoverflow.com/questions/1599287/create-read-and-erase-cookies-with-jquery