常用的一个cookie 对象,还有path 兼容性问题
//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();
}
}
};
cookie path设置必知:
Firefox 的path 可以随便设置,就算path不在当前location路径也行;
到了chrome下就不能随便了,chrome的path 只能设置当前location中存在的路径,例如:
我当前所在登录页
www.***.com/jr/login/
path设置:
ck.set("username","djh","/");
ck.set("username","djh","/jr");
ck.set("username","djh","/jr/");
ck.set("username","djh","/jr/login");
ck.set("username","djh","/jr/login/");
以上设置都是可以生效的。
所以为了兼容性。设置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了。