【问题标题】:JavaScript set and get cookies?JavaScript 设置和获取 cookie?
【发布时间】:2012-06-29 03:49:02
【问题描述】:

我有一个保存 cookie 的功能

    cookievalue= escape(document.passwordCheck.oldPassword.value) + ";";
    document.cookie="oldCookie=" + cookievalue
    cookievalue= escape(document.passwordCheck.oldPassword.value) + ";";
    document.cookie="newCookie=" + cookievalue

如何检索 oldCookie 和 newCookie 的数据?

【问题讨论】:

标签: javascript html cookies


【解决方案1】:

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

ffoo=bar; foo=baz

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

现在我要做的是:首先,您需要了解 cookie 如何传输的语法。 Netscape 的原始规范(只有像 this one at haxx.se 这样的副本)使用分号分隔多个 cookie,而每个名称/值对具有以下语法:

姓名=
该字符串是不包括分号、逗号和空格的字符序列。如果需要在名称或值中放置此类数据,建议使用 URL 样式%XX 编码等编码方法,但无需定义或要求编码。

因此,将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];
}

来源:https://stackoverflow.com/a/4004010

【讨论】:

  • 来源与否,您不应该撕毁其他答案。如果问题重复,请在评论中链接到现有问题。
  • @JonathanLonowski 当然... :) 将从下一个开始! :)
【解决方案2】:

来自http://www.w3schools.com/js/js_cookies.asp

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

【讨论】:

    【解决方案3】:

    使用 cookie 库或其他函数来获取价值。

    http://www.java2s.com/Code/JavaScript/Development/Cookiesetdeletegetvalueandcreate.htm

    function getCookieVal (offset) {
      var endstr = document.cookie.indexOf (";", offset);
      if (endstr == -1) { endstr = document.cookie.length; }
      return unescape(document.cookie.substring(offset, endstr));
    }
    
    function getCookie (name) {
      var arg = name + "=";
      var alen = arg.length;
      var clen = document.cookie.length;
      var i = 0;
      while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
          return getCookieVal (j);
          }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
        }
         return null;
      }
    

    【讨论】:

    • 你不应该用大写字母开始一个非构造函数名称
    猜你喜欢
    • 2017-09-05
    • 2018-12-21
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2021-02-09
    相关资源
    最近更新 更多