设置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的作用域限制在和当前文档同目录的文档中





 

posted on 2016-03-30 21:44  wts_crazy  阅读(176)  评论(0编辑  收藏  举报