2009年5月8日 星期五

JavaScript 寫入, 讀取, 刪除 Cookie 值

function SetCookie(name,value,expiry,path,domain,secure){
var NameString = name + "=" + value;
var ExpiryString = (expiry == null) ? "" : " ;expires = "+ expiry.toGMTString();
var PathString = (path == null) ? "" : " ;path = "+ path;
var DomainString = (path == null) ? "" : " ;domain = "+ domain;
var SecureString = (secure) ?";secure" :"";
document.cookie = NameString + ExpiryString + PathString + DomainString + SecureString;
}

function GetCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
if(arr != null) return unescape(arr[2]); return null;
}

function DelCookie(name){
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

2 則留言:

匿名 提到...

you saved me.
many scripts not actually delete cookie, your code works, thank you!

小麥 提到...

Thank you!