使用JS在本地读写cookie

来源:赵克立博客 分类: 前端开发 标签:js函数Sublime发布时间:2014-04-30 01:04:00最后更新:2019-06-18 19:46:47浏览:741
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2019-06-18 19:46:47
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
/**
 * js写cookies
 * @param    string   name  键
 * @param    string   value 值
 * @param    int       seconds 过期时间,true:10年,int:单位秒,默认跟随会话
 */
function writeCookie(name, value, seconds) {
    var expire = "";
    if (seconds == true) {
        expire = new Date((new Date()).getTime() + 3600000 * 24 * 365 * 10);
    } else {
        expire = new Date((new Date()).getTime() + seconds * 1000);
    }
    if (expire) {
        document.cookie = name + "=" + encodeURI(value) + "; expires=" + expire.toGMTString() + ";path=/";
    } else {
        document.cookie = name + "=" + encodeURI(value);
    }
}
/**
 * 用cookies名字读它的值
 * @param  string name 键名
 * @return string      如果没有设置过返回null,设置过的话返回字符串
 */
function readCookie(name) {
    var cookieValue = null;
    var search = "; " + name + "=";
    var cookies = document.cookie;
    if (cookies.length > 0) {
        var offset = cookies.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            var end = cookies.indexOf(";", offset);
            if (end == -1) end = cookies.length;
            cookieValue = unescape(cookies.substring(offset, end))
        }
    }
    return cookieValue;
}

微信号:kelicom QQ群:215861553 紧急求助须知
Win32/PHP/JS/Android/Python