js函数收藏:获取cookie值

时间:2023-02-10 21:57:30
//先设置一段子cookie
var d = new Date();
d.setMonth(d.getMonth() + 1);
d = d.toGMTString();
var a = "name:a, age:20, addr:beijing";
var c = "user=" + escape(a);
c += ";" + "expires=" + d;
document.cookie = c;

//读取所有cookie信息,包括子cookie信息的值
//返回值:对象(键:每个cookie变量【包括子cookie中的键】,值:每个cookie变量的值【包括子cookie中的值】)
function getSubCookie(){
    var a = document.cookie.split(";");
    var o = {};
    for (var i = 0; i < a.length; i++){ //遍历cookie信息数组
        a[i] && (a[i] = a[i].replace(/(^\s*)|(\s*$)/g,''));
        //清除头部空格符
        var b = a[i].split("=");
        var c = b[1];
        c && (c = c.replace(/(^\s*)|(\s*$)/g,''));
        c = unescape(c);
        //如果c中不包含逗号(不是子cookie),直接把c作为cookie变量的值存入对象
        if(!/\,/gi.test(c)){
            o[b[0]] = b[1];
        }else{
            var d = c.split(",");
            for(var j=0; j<d.length; j++){
                var e = d[j].split(":");
                e[0] && (e[0] = e[0].replace(/(^\s*)|(\s*$)/g,''));
                o[e[0]] = e[1];
            }
        }
    }
    return o;
}

 代码片段2:封装cookie存取功能

//封装cookie存取功能,可以写入cookie,读取cookie,也可以删除cookie
function Cookie(name, value, options){
    if(typeof value != 'undefined'){
        options = options || {};
        if(value === null){
            options.expires = -1;
        }
        var expires = '';
        if(options.expires && (typeof options.expires == 'number' || options.expires.toUTCString())){
            var date;
            if(typeof options.expires == 'number'){
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            }else{
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path?'; path='+options.path:'';
        var domain =  options.domain?'; domain='+options.domain:'';
        var secure = options.secure?'; secure':'';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }else{
        var CookieValue = null;
        if(document.Cookie && document.Cookie != ''){
            var Cookies = document.Cookie.split(";");
            for( var i = 0; i < Cookies.length; i++){
                var Cookie = (Cookies[i] || "").replace(/^\s+|\s+$/g, "");
                //这个if写的屌
                if(Cookie.substring(0, name.length + 1) == (name + '=')){
                    CookieValue = decodeURIComponent(Cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return CookieValue;
    }
}

//设置cookie
Cookie('user', 'hebe', {expires:10, path:"/", domain:"baidu.com", secure: true});
//读取cookie
Cookie('user');
//删除cookie
Cookie('user', null);