首页 > 其他 > 详细

cookie写入存储与读取键值对函数

时间:2014-08-26 19:28:36      阅读:633      评论:0      收藏:0      [点我收藏+]
function setCookie(name, value, expires, path, domain, secure){
    var cookieName = encodeURIComponent(name) + ‘=‘ + encodeURIComponent(value);
    if(expires instanceof Date){
        cookieName += ‘; expires=‘ + expires;
    }
    if(path){
        cookieName += ‘; path=‘ + path;
    }
    if(domain){
        cookieName += ‘; domain=‘ + domain;
    }
    if(secure){
        cookieName += ‘; secure‘;
    }
    document.cookie=cookieName;
}

function getCookie(name){
    var cookieName = encodeURIComponent(name) + ‘=‘;
    var cookieStart = document.cookie.indexOf(cookieName);
    var cookieValue = null;

    if(cookieStart>-1){
        var cookieEnd = document.cookie.indexOf(‘;‘, cookieStart);
        if(cookieEnd == -1){
            cookieEnd = document.cookie.length;
        }
        cookieValue = document.cookie.substring(cookieStart + cookieName.length , cookieEnd);
    }
    return cookieValue;
}

console.log(getCookie(‘email‘));



function setCookieDate(day){
    var date = null;
    if(typeof day == ‘number‘ && day>0){
        date = new Date();
        date.setDate(date.getDate()+day);
    }else{
        throw new Error(‘您传递的天数不合法!必须是数字且大于0‘);
    }
    return date.toGMTString();
}
setCookie(‘user‘, ‘乐乐乐‘, setCookieDate(7));
setCookie(‘url‘, ‘yfdsae.com‘, setCookieDate(7));
setCookie(‘email‘, ‘yc69@13.com‘, setCookieDate(7));

PS: name=value; [expires=time; path=path; domain=‘域名‘; secure=‘安全加密链接‘;]

cookie写入存储与读取键值对函数

原文:http://www.cnblogs.com/oceanden/p/3937829.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!