您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Javascript getCookie函数

Javascript getCookie函数

W3CSchool的函数错误。如果存在多个具有相同后缀的cookie,则失败:

ffoo=bar; foo=baz

当您搜索foo它时,将返回 ffoo 而不是 foo 的值。

现在,这就是我要做的事情:首先,您需要了解cookie传输方式的语法。netscape的原始规范(haxx.se上只有这样的副本可用)使用分号分隔多个cookie,而每个名称/值对具有以下语法:

名称= 值此

字符串是一个字符序列,不包括分号,逗号和空格。如果需要在名称或值中放置此类数据,%XX则建议使用某些编码方法,例如URL样式编码,尽管未定义或不需要编码。

因此,document.cookie以分号或逗号分隔字符串是一个可行的选择。

除此之外,RFC 2109还规定了cookie用分号或逗号分隔:

cookie          =       "Cookie:" cookie-version
                        1*((";" | ",") cookie-value)
cookie-value    =       NAME "=" VALUE [";" path] [";" domain]
cookie-version  =       "$Version" "=" value
NAME            =       attr
VALUE           =       value
path            =       "$Path" "=" value
domain          =       "$Domain" "=" value

尽管两者都允许,但最好使用逗号,因为逗号是HTTP中列表项的认分隔符。

注意:为了向后兼容,Cookie标头中的分隔符;到处都是分号()。服务器还应接受逗号(,)作为cookie值之间的分隔符,以实现将来的兼容性。

此外,名称/值对还有一些其他限制,因为 VALUE 也可以是RFC 2616中指定的带引号的字符串:

attr        =     token
value       =     token | quoted-string

因此,这两个Cookie版本需要分别处理:

if (typeof String.prototype.trimLeft !== "function") {
    String.prototype.trimLeft = function() {
        return this.replace(/^\s+/, "");
    };
}
if (typeof String.prototype.trimRight !== "function") {
    String.prototype.trimRight = function() {
        return this.replace(/\s+$/, "");
    };
}
if (typeof array.prototype.map !== "function") {
    array.prototype.map = function(callback, thisArg) {
        for (var i=0, n=this.length, a=[]; i<n; i++) {
            if (i in this) a[i] = callback.call(thisArg, this[i]);
        }
        return a;
    };
}
function getCookies() {
    var c = document.cookie, v = 0, cookies = {};
    if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
        c = RegExp.$1;
        v = 1;
    }
    if (v === 0) {
        c.split(/[,;]/).map(function(cookie) {
            var parts = cookie.split(/=/, 2),
                name = decodeURIComponent(parts[0].trimLeft()),
                value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
            cookies[name] = value;
        });
    } else {
        c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) {
            var name = $0,
                value = $1.charAt(0) === '"'
                          ? $1.substr(1, -1).replace(/\\(.)/g, "$1")
                          : $1;
            cookies[name] = value;
        });
    }
    return cookies;
}
function getCookie(name) {
    return getCookies()[name];
}
javascript 2022/1/1 18:53:01 有443人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶