JavaScript設定、単値と多値cookieを取得、クリアする方法
3218 ワード
余計なことを言わないで、直接コードを貼ります.
具体的なコードは以下の通りです.
具体的なコードは以下の通りです.
var CookieUtil = (function () {
var Cookie = function () {
// cookie
this.get = function(name) {
var start = document.cookie.indexOf(encodeURIComponent(name)) ;
var end = document.cookie.indexOf(';', start) ;
if(end == -) {
end = document.cookie.length;
}
return decodeURIComponent(document.cookie.substring(start+name.length+,end));
};
// cookie
this.set = function(name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
//
if(expires == undefined) {
var date = new Date();
date.setTime(date.getTime() + ****);
expires = date ;
}
if(expires instanceof Date) {
cookieText += "; expires=" + expires.toGMTString();
}
if(path != undefined) {
cookieText += "; path=" + path;
}
if(domain != undefined) {
cookieText += "; domain" + domain;
}
if(secure != undefined) {
cookieText += "; secure";
}
document.cookie = cookieText;
};
// cookie
this.unset = function(name, path, domain, secure) {
this.set(name, '', new Date(), path, domain, secure );
};
// cookie
this.setAll = function(name, subCookies, expires, path, domain, secure) {
var cookieText = ";" + encodeURIComponent(name) + "=",
arr = new Array();
for(var attr in subCookies) {
arr.push([encodeURIComponent(attr)] + ":" + encodeURIComponent(subCookies[attr]));
}
this.set(name, arr.join('&'), expires, path, domain, secure);
};
// cookie
this.getAll = function(name) {
var obj = {};
var arr = this.get(name).split('&');
for(var i = , len = arr.length; i < len; i++) {
var tmpArr = arr[i].split(':');
obj[decodeURIComponent(tmpArr[])] = decodeURIComponent(tmpArr[]);
}
return obj;
};
// cookie cookie
this.getSub = function(name, subname) {
var obj = this.getAll(name);
return obj[subname];
};
// cookie
this.unsetAll = function(name,path,domain,secure) {
this.unset(name, '', new Date(), path, domain, secure);
};
// cookie cookie
this.unsetSub = function(name, subname,path, domain, secure) {
var obj = this.getAll(name);
delete obj[subname];
this.setAll(name, obj, null, path, domain, secure);
};
};
return new Cookie();
})();
以上のコードは、JavaScriptの設定、取得、クリア、多値クッキーの設定方法を紹介します.どこか不明なところがありましたら、メッセージをください.