var cookie = {
getAll: function() {
var arr = unescape(document.cookie).split("; "),
o = {};
for (var i = 0, len = arr.length; i < len; i++) {
var a = arr[i],
index = a.indexOf("="),
b = a.substr(0, index),
c = a.substr(index + 1);
o[b] = c
}
return o;
},
save: function(obj, day, path) {
for (var a in obj) {
var b = obj[a];
this.set(a, b, day, path);
}
},
dels: function(arr, path) {
for (var i in arr) {
var a = arr[i];
this.del(a, path);
}
},
set: function (key, val, seconds = 24 * 60 * 60, path) {
if (val == null || val == undefined) return;
var k = key,
s = seconds,
e = new Date();
e.setSeconds(e.getSeconds() + s);
val instanceof Array && (val = val.join("||")), val instanceof Object && (val = JSON.stringify(val));
document.cookie = k + "=" + escape(val.toString()) + ((s == null) ? "" : ";expires=" + e.toGMTString()) + "; path=/" + (path || "");
},
get: function(key) {
var k = key;
if (document.cookie.length > 0) {
var s = document.cookie.indexOf(k + "=");
if (s != -1) {
s = s + k.length + 1;
var e = document.cookie.indexOf(";", s);
if (e == -1) e = document.cookie.length;
return unescape(document.cookie.substring(s, e));
}
}
return "";
},
getJOSN: function(key) {
return JSON.parse(this.get(key) || '{}');
},
getArray: function(key) {
return this.get(key).split("||");
},
del: function(key, path) {
var k = key,
e = new Date(),
val = this.get(k);
e.setTime(e.getTime() - 1);
if (val != null) document.cookie = k + "=" + val + ";expires=" + e.toGMTString() + "; path=/" + (path || "");
},
clearAll: function(path) {
var k = document.cookie.match(/[^ =;]+(?=\=)/g);
if (k) {
for (var i = k.length; i--;) document.cookie = k[i] + '=0;expires=' + new Date(0).toUTCString() + "; path=/" + (path || "");
}
},
setToken: function(val, day, path) {
this.set("token", val, day, path)
},
getToken: function(path) {
return this.get("token", path)
},
setTempToken: function(val, day, path) {
this.set("tempToken", val, day, path)
},
getTempToken: function(path) {
return this.get("tempToken", path)
}
}
/*測試用例*/
cookie.save({username: "admin", password: "123456"}, 365);
/*批量儲存*/
cookie.dels(["username", "password"]);
/*批量刪除*/
console.log(cookie.getAll());//獲取所有快取資料轉換為物件