设置cookie和获取cookie
Posted wts_crazy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设置cookie和获取cookie相关的知识,希望对你有一定的参考价值。
/**
* Created by admin on 2016/3/30.
*/
function setCookie(name,value,dayToLive){
var cookie = name + "=" +encodeURIComponent(value);
if(typeof dayToLive === "number"){
cookie += ";max-age="+(dayToLive * 24 * 60 * 60);
}
document.cookie = cookie;
}
function getCookies(){
var cookies = {};
var all = document.cookie;
if(all === ""){
return cookies;
}
var list = all.split("; ");
for(var i=0,len=list.length;i<len;i++){
var cookie = list[i];
var p = cookie.indexOf("=");
var name = cookie.substring(0,p);
var value = decodeURIComponent(cookie.substring(p+1));
cookies[name] = value;
}
return cookies;
}
setCookie("aaa","111",5);
setCookie("bbb","222",5);
var cookies = getCookies();
for(var i in cookies){
//注意!!!火狐浏览器下会默认多出两个私有属性,但均是以"_"开头
if(cookies.hasOwnProperty(i) && i.indexOf("_") != 0){
// document.cookie = i+"=0;expires="+new Date(0).toUTCString();
alert(i+" : " + cookies[i]);
}
}
//当单独针对IE写缓存时,可以使用IE userData,IE userData的作用域限制在和当前文档同目录的文档中
以上是关于设置cookie和获取cookie的主要内容,如果未能解决你的问题,请参考以下文章