Javascript getCookie函数 [英] Javascript getCookie functions

查看:201
本文介绍了Javascript getCookie函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现两个功能可以通过Javascript获取Cookie数据,一个在 w3schools.com 上,一个在 quirksmode.org

我想知道我应该使用哪一个?

I found two functions to get cookie data with Javascript, one on w3schools.com and one on quirksmode.org
I would like to know which one I should use?

例如,我相信我在某处读到了一些浏览器分割; 分号的问题?

For example I believe I read somewhere that there was a problem with some browsers splitting the ; semicolon?

w3schools:

w3schools:

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 "";
}

quirksmode:

quirksmode:

function readCokie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


推荐答案

W3CSchool的功能错误。如果有多个具有相同后缀的Cookie,则会失败:

The function from W3CSchool is wrong. It fails if there are multiple cookies that have the same suffix like:

ffoo=bar; foo=baz

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

When you search for foo it will return the value of ffoo instead of foo.

现在这里是我要做的:所有,你需要了解如何传输cookie的语法。 Netscape的原始规范(只有副本可用,如这一个在haxx.se )使用分号分隔多个Cookie,每个名称/值对具有以下语法:

Now here is what I would do: First of all, you need get to know the syntax of how cookies are transported. Netscape’s original specification (there are only copies available like this one at haxx.se) uses semicolons to separate multiple cookies while each name/value pair has the following syntax:


NAME = VALUE

此字符串是一系列字符,不包括分号,逗号和空格。如果需要在名称或值中放置此类数据,则建议使用某些编码方法,例如URL style %XX 编码,但不定义或需要编码。 / p>

NAME=VALUE
This string is a sequence of characters excluding semi-colon, comma and white space. If there is a need to place such data in the name or value, some encoding method such as URL style %XX encoding is recommended, though no encoding is defined or required.

因此以分号或逗号分隔 document.cookie

So splitting document.cookie string at semi-colons or commas is a viable option.

除此之外, RFC 2109 也指定Cookie由分号或逗号分隔:

Besides that, RFC 2109 does also specify that cookies are separated by either semi-colons or commas:


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中列表项的默认分隔符。

Although both are allowed, commas are preferred as they are the default separator of list items in HTTP.


注意:为了向后兼容,头
是分号(; )无处不在。服务器还应接受逗号(
作为cookie值之间的分隔符,以便将来兼容。

Note: For backward compatibility, the separator in the Cookie header is semi-colon (;) everywhere. A server should also accept comma (,) as the separator between cookie-values for future compatibility.

此外,名称/值对还有一些限制,因为 VALUE 也可以是 RFC 2616

Furthermore, the name/value pair has some further restrictions as the VALUE can also be a quoted string as specified in RFC 2616:


attr        =     token
value       =     token | quoted-string


所以这两个cookie版本需要单独处理:

So these two cookie versions need to be treated separately:

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 getCookie函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆