Javascript 如何更新和删除cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7215547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:22:45  来源:igfitidea点击:

How to update and delete a cookie?

javascriptcookies

提问by San Jay

I need help to know how to update values and how to delete a cookiecreated from this code! I'm new to JavaScript so it's great if anyone can help me.

我需要帮助才能知道如何更新值以及如何删除从此代码创建的cookie!我是 JavaScript 的新手,所以如果有人可以帮助我,那就太好了。

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

function setCookie(c_name,value,exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays==null) ? "" : ";                                    expires="+exdate.toUTCString());
   document.cookie=c_name + "=" + c_value;
 }

function check2Cookie() {
     var username=getCookie("username");
     if (username!=null && username!="") {
         username= "0";
         setCookie("username",username,1000);
     }
     else {
         username=" ";
         if (username!=null && username!="") {
               username= "0";
               setCookie("username",username,1000);
         }
     }
}

This is the code for cookie creation.

这是创建 cookie 的代码。

Code for creating is setCookie("username",username,1000);

创建代码是 setCookie("username",username,1000);

Now how to update this cookie and delete this cookie.

现在如何更新这个 cookie 和删除这个 cookie。

回答by jordanb

The cookie API is kind of lame. Let me clarify...

cookie API 有点蹩脚。让我澄清...

You don't update cookies; you overwritethem:

您不更新 cookie;你覆盖它们:

    document.cookie = "username=Arnold"; // Create 'username' cookie
    document.cookie = "username=Chuck"; // Update, i.e. overwrite, the 'username' cookie to "Chuck"

You also don't delete cookies; you expirethem by setting the expireskey to a time in the past (-1 works too).

您也不会删除 cookie;您过期通过设置这些expires关键的时间过去(-1工作太)。

Source: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

来源:https: //developer.mozilla.org/en-US/docs/Web/API/document.cookie

回答by Dave Lasley

http://www.quirksmode.org/js/cookies.html

http://www.quirksmode.org/js/cookies.html

update would just be resetting it using createCookie

更新只会使用 createCookie 重置它

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

回答by epascarello

http://www.quirksmode.org/js/cookies.html

http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

回答by xiaoyu2er

check this out A little framework: a complete cookies reader/writer with full Unicode support

看看这个一个小框架:一个完整​​的 cookie 读取器/写入器,具有完整的 Unicode 支持

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\$&") + "\s*\=\s*([^;]*).*$)|^.*$"), "")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\$&") + "\s*\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};