//cookie
var ck = {
getObj:function() {
var ck = document.cookie;
var obj = {};
if(ck!=""){
var ck_array = ck.split(";");
var ck_json = ck_array.map(function(e){
var arry = e.split("=");
obj[arry[0].trim()]=arry[1].trim();
return obj;
});
}
return obj;
},set:function(name, value,options) {
var defaults = {
path: null,
domain: null//默認是當前域,
};
var opt = $.extend({},defaults,options);
var exist = this.getObj().name;
var expire = new Date();
expire.setDate(expire.getDate() + opt.day);//默認是會話cookie
if(exist=="undefined") {
document.cookie = name + '=' + value + ';expires=' + expire.toGMTString() + ';path=' + opt.path ;
}else {
this.del(name);
document.cookie = name + '=' + value + ';expires=' + expire.toGMTString() + ';path=' + opt.path ;
}
},del:function(name) {
var exist = this.getObj().name;
if(exist!="undefined") {
var clear = new Date();
clear.setTime(clear.getTime()-1000);
document.cookie = name + '= 5 ;expires=' + clear.toGMTString();
}
}
};
Firefox 的path 能夠隨便設置,就算path不在當前location路徑也行;chrome
到了chrome下就不能隨便了,chrome的path 只能設置當前location中存在的路徑,例如:json
我當前所在登陸頁瀏覽器
www.***.com/jr/login/cookie
path設置:dom
ck.set("username","djh","/");this
ck.set("username","djh","/jr");spa
ck.set("username","djh","/jr/");code
ck.set("username","djh","/jr/login");blog
ck.set("username","djh","/jr/login/");get
以上設置都是能夠生效的。
因此爲了兼容性。設置path的時候,務必設置location中存在的路徑,或者直接設置
ck.set("username","djh","/");
這樣就整個域都能取到這個cookie;
ps:cookie的path若是不設置或者設置無效的話,瀏覽器默認是當前位置 /jr/login/
另外cookie的獲取也只能在cookie的path路徑下的頁面才能拿獲得
例如我剛剛在登陸頁設置的cookie
ck.set("username","djh","/jr/login");
那麼我在會員中心頁 www.***.com/jr/uc/ ,就拿不了這個username的cookie了。