码迷,mamicode.com
首页 > 编程语言 > 详细

javascript设置和获取cookie值

时间:2014-09-21 20:27:01      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   java   ar   div   sp   art   

//设置cookie
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=‘ + true;
    }
    document.cookie = cookieName;
}

//过期时间
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;
}

setCookie(‘user‘,‘小飞‘,setCookieDate(7));
setCookie(‘url‘,‘baidu.com‘,setCookieDate(7));
setCookie(‘email‘,‘1253185@qq.com‘,setCookieDate(7));

//获取cookie
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 = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length,cookieEnd));
    }
    return cookieValue;
}

alert(getCookie(‘email‘));

 

javascript设置和获取cookie值

标签:style   blog   color   io   java   ar   div   sp   art   

原文地址:http://www.cnblogs.com/littlefly/p/3984831.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!