JS实现cookie的CRUD(需要注意path)

其实也没太大难度,主要注意设置cookie的时候需要统一path,因为现在很多pathinfo模式的url,会导致path不统一,你在 www.domain.com/foo 路径下设置的cookie在www.domain.com/bar下可能会读取不到,因为path可能不同,默认 / 最好

//增加或者更新cookie
function setCookie(c_name, value, expiredays, path) {
    var expiredays = arguments[2] ? arguments[2] : 1;
    var path = arguments[3] ? arguments[3] : '/';
    console.log(expiredays, path);
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays * 24 * 60 * 60 * 1000);
    document.cookie = c_name + "=" + escape(value) +
    ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString() + ";path=" + path);
}

//获取cookie
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

//删除cookie
function delCookie(c_name, path) {
    var path = arguments[1] ? arguments[1] : '/';
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(c_name);
    if (cval != null) document.cookie = c_name + "=" + cval + ";expires=" + exp.toGMTString() + ";path=" + path;
}

setCookie("name", "sallency");

getCookie("name");

delCookie("name");

评论

暂无评论