首页 > 代码库 > Cookie 的设置和获取

Cookie 的设置和获取

获取:var userName = getCookieValue("userName");

设置:setCookie("userName",equpid,24,"/");

//hours为空字符串时,cookie的生存期至浏览器会话结束。hours为数字0时,建立的是一个失效的cookie,这个cookie会覆盖已经建立过的同名、同path的cookie(如果这个cookie存在)。
function setCookie(name,value,hours,path){
    var name = escape(name);
    var value =http://www.mamicode.com/ escape(value);
    var expires = new Date();
    expires.setTime(expires.getTime() + hours*3600000*3600);
    path = path == "" ? "" : ";path=" + path;
    _expires = (typeof hours) == "string" ? "" : ";expires=" + expires.toUTCString();
    document.cookie = name + "=" + value + _expires + path;
}//新建cookie
function getCookieValue(name){
    var name = escape(name);
    var allcookies = document.cookie;
    name += "=";
    var pos = allcookies.indexOf(name);
    if (pos != -1){
        var start = pos + name.length;
        var end = allcookies.indexOf(";",start);
        if (end == -1) end = allcookies.length;
        var value =http://www.mamicode.com/ allcookies.substring(start,end);
        return unescape(value);
    }
    else return "";
}//获取cookie值
function deleteCookie(name,path){
    var name = escape(name);
    var expires = new Date(0);
    path = path == "" ? "" : ";path=" + path;
    document.cookie = name + "="+ ";expires=" + expires.toUTCString() + path;
}//删除cookie

Cookie 的设置和获取