簡體   English   中英

JavaScript設置並獲取Cookie?

[英]JavaScript set and get cookies?

我有一個保存cookie的功能

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

如何檢索oldCookie和newCookie的數據?

W3CSchool的功能是錯誤的。 如果有多個cookie具有相同的后綴,則會失敗,如:

ffoo=bar; foo=baz

當你搜索foo ,它將返回ffoo而不是foo的值。

現在我要做的是:首先,您需要了解cookie的傳輸方式。 Netscape的原始規范(只有像haxx.se這樣的副本可用)使用分號分隔多個cookie,而每個名稱/值對具有以下語法:

NAME = VALUE
此字符串是一系列字符,不包括分號,逗號和空格。 如果需要在名稱或值中放置此類數據,則建議使用某種編碼方法,例如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

來自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);
        }
    }
}

使用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;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM