Cookie的设置和获取

function setCookie(c_name, value, expiredays){
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
}
function getCookie(c_name, value, expiredays){
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=")

        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            var c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length

            try {
                return JSON.parse(unescape(document.cookie.substring(c_start, c_end)))
            } catch(e) {
                return null
            }
        }
    }
    return null
}
var KEY = "USER_INFO";
var value = {
    name:"张三",
    tel:"15921391061",
    pwd:"wjf123465"
}
setCookie(KEY, JSON.stringify(value), 1);

var userInfo=getCookie(KEY);
console.log(userInfo);// json
setCookie(KEY, JSON.stringify(value), -1);
var userInfo=getCookie(KEY);
console.log(userInfo);// null

 

posted @ 2017-11-23 18:40  逗伴不是瓣  阅读(482)  评论(0编辑  收藏  举报