Javascript 如何从cookie中创建和读取值?

Javascript 如何从cookie中创建和读取值?,javascript,cookies,Javascript,Cookies,如何在JavaScript中创建和读取cookie中的值?以下是可用于创建和检索cookie的函数 function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; exp

如何在JavaScript中创建和读取cookie中的值?

以下是可用于创建和检索cookie的函数

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

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

或纯Javascript:

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 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);
      }
   }
}
函数setCookie(c_名称、值、exdays)
{
var exdate=新日期();
exdate.setDate(exdate.getDate()+exdays);
var c_value=escape(value)+(exdays==null)?:(“expires=“+exdate.toutString());
document.cookie=c_name+“=”+c_值;
}
函数getCookie(c_名称)
{
变量i,x,y,ARRcookies=document.cookie.split(“;”);
对于(i=0;iMozilla创建了一个示例,以及如何使用它的示例

一旦包含在页面上,您可以设置cookie:

docCookies.setItem(name, value);
docCookies.getItem(name);
docCookies.removeItem(name);
阅读cookie:

docCookies.setItem(name, value);
docCookies.getItem(name);
docCookies.removeItem(name);
或删除cookie:

docCookies.setItem(name, value);
docCookies.getItem(name);
docCookies.removeItem(name);
例如:

// sets a cookie called 'myCookie' with value 'Chocolate Chip'
docCookies.setItem('myCookie', 'Chocolate Chip');

// reads the value of a cookie called 'myCookie' and assigns to variable
var myCookie = docCookies.getItem('myCookie');

// removes the cookie called 'myCookie'
docCookies.removeItem('myCookie');
请参阅有关的更多示例和详细信息


此简单js文件的一个版本是。

readCookie的改进版本:

function readCookie( name )
{
    var cookieParts = document.cookie.split( ';' )
    ,   i           = 0
    ,   part
    ,   part_data
    ,   value
    ;

    while( part = cookieParts[ i++ ] )
    {
        part_data = part.split( '=' );

        if ( part_data.shift().replace(/\s/, '' ) === name )
        {
            value = part_data.shift();
            break;
        }

    }
    return value;
}
当你找到你的cookie值并返回它的值时,它应该立即中断。在我看来,双分割非常优雅

if条件下的替换为空白微调,以确保其正确匹配

函数setCookie(cname、cvalue、exdays){
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}
var d=新日期(); d、 设置时间(d.getTime()+(exdays*24*60*60*1000)); var expires=“expires=“+d.togmString(); document.cookie=cname+“=”+cvalue+”;“+expires; } 函数getCookie(cname){ 变量名称=cname+“=”; var ca=document.cookie.split(“;”);
对于(var i=0;i < p>),我使用这个对象。值被编码,因此在服务器端读写时必须考虑它。

cookie = (function() {

/**
 * Sets a cookie value. seconds parameter is optional
 */
var set = function(name, value, seconds) {
    var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
    document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
};

var map = function() {
    var map = {};
    var kvs = document.cookie.split('; ');
    for (var i = 0; i < kvs.length; i++) {
        var kv = kvs[i].split('=');
        map[kv[0]] = decodeURIComponent(kv[1]);
    }
    return map;
};

var get = function(name) {
    return map()[name];
};

var remove = function(name) {
    set(name, '', -1);
};

return {
    set: set,
    get: get,
    remove: remove,
    map: map
};

})();
cookie=(函数(){
/**
*设置cookie值。秒参数是可选的
*/
变量集=函数(名称、值、秒){
var expires=seconds?';expires='+新日期(new Date().getTime()+seconds*1000);
document.cookie=name+'='+encodeURIComponent(value)+expires+';path=/';
};
var map=function(){
var-map={};
var kvs=document.cookie.split(“;”);
对于(变量i=0;i
我已经多次使用此线程的公认答案。这是一段很棒的代码:简单且可用。但我通常使用和ES6以及模块,因此,如果您像我一样,这里有一些代码可以复制,以便使用ES6更快地开发

用ES6重写为模块:

export const createCookie = ({name, value, days}) => {
  let expires;
  if (days) {
    let date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = '; expires=' + date.toGMTString();
  } else {
    expires = '';
  }
  document.cookie = name + '=' + value + expires + '; path=/';
};

export const getCookie = ({name}) => {
  if (document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(name + '=');
    if (c_start !== -1) {
      c_start = c_start + name.length + 1;
      let 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 '';
};
在此之后,您只需将其作为任何模块导入即可(路径当然可能会有所不同):

这里有一个代码

函数getCookie(名称){ 名称=名称+“=”; var cookies=document.cookie.split(“;”);
对于(var i=0;i最低限度和全功能ES6方法:

const setCookie = (name, value, days = 7, path = '/') => {
  const expires = new Date(Date.now() + days * 864e5).toUTCString()
  document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path
}

const getCookie = (name) => {
  return document.cookie.split('; ').reduce((r, v) => {
    const parts = v.split('=')
    return parts[0] === name ? decodeURIComponent(parts[1]) : r
  }, '')
}

const deleteCookie = (name, path) => {
  setCookie(name, '', -1, path)
}

对于那些需要保存对象如{foo:'bar'}的人,我将分享我编辑过的@KevinBurke的答案。我添加了JSON.stringify和JSON.parse,仅此而已

cookie = {

    set: function (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 + "=" + JSON.stringify(value) + expires + "; path=/";
    },

    get : function(name){
        var nameEQ = name + "=",
            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  JSON.parse(c.substring(nameEQ.length,c.length));
        }

        return null;
    }

}

ES6中读取cookie的简单方法

function getCookies() {
    var cookies = {};
    for (let cookie of document.cookie.split('; ')) {
        let [name, value] = cookie.split("=");
        cookies[name] = decodeURIComponent(value);
    }
    console.dir(cookies);
}
我已经习惯了成功

<script src="/path/to/js.cookie.js"></script>
<script>
  Cookies.set('foo', 'bar');
  Cookies.get('foo');
</script>

Cookies.set('foo','bar');
Cookies.get('foo');
ES7,为get()使用正则表达式。基于


用法-Cookie.get(名称、值[、选项]):
选项支持所有标准cookie选项并添加“天”:

  • 路径:“/”-任何绝对路径。默认值:当前文档位置
  • :“sub.example.com”-不能以点开头。默认值:当前主机没有子域
  • 安全:true-仅通过https提供cookie。默认值:false
  • :cookie过期前2天。默认值:会话结束。
    设置过期时间的其他方法:
    • 到期日期:“Sun,2018年2月18日16:23:42 GMT”-到期日期作为GMT字符串。
      当前日期可以通过以下方式获取:new date(date.now()).toutString()
    • “最大年龄”:30-与天相同,但以秒为单位,而不是以天为单位
其他答案使用“expires”而不是“max age”来支持旧版IE。这种方法需要ES7,所以IE7无论如何都不支持(这没什么大不了的)

注意:支持将“=”和“{:}”等有趣字符作为cookie值,并且正则表达式处理前导和尾随空格(来自其他LIB)。
如果要存储对象,请使用和JSON.stringify和JSON.parse在对象之前和之后对其进行编码,编辑上述内容,或添加其他方法。例如:

Cookie.getJSON = name => JSON.parse(Cookie.get(name))
Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts);

我编写了简单的cookieUtils,它有三个函数用于创建cookie、读取cookie和删除cookie

var CookieUtils = {
    createCookie: function (name, value, expireTime) {
        expireTime = !!expireTime ? expireTime : (15 * 60 * 1000); // Default 15 min
        var date = new Date();
        date.setTime(date.getTime() + expireTime);
        var expires = "; expires=" + date.toGMTString();
        document.cookie = name + "=" + value + expires + "; path=/";
    },
    getCookie: function (name) {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) {
            return parts.pop().split(";").shift();
        }
    },
    deleteCookie: function(name) {
        document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }
};

一种厚颜无耻且简单的解读饼干的方式可能是:

let username, id; 
eval(document.cookie); 
console.log(username + ", " + id); // John Doe, 123
如果您知道您的cookie包含类似以下内容,则可以使用此选项:
username=“John Doe”id=123;
。请注意,cookie中的字符串可能需要引号。这可能不是推荐的方法,但可用于测试/学习。

以下是所提到的示例

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
函数setCookie(cname、cvalue、exdays){
var d=新日期();
d、 设置时间(d.getTime()+(exdays*24*60*60*1000));
var expires=“expires=“+d.toutString();
document.cookie=cname+“=”+cvalue+”;“+expires+”;path=/”;
}
函数getCookie(cname){
变量名称=cname+“=”;
var decodedCookie=decodeURIComponent(document.cookie);
var ca=decodedCookie.split(“;”);
对于(var i=0;i您可以使用我的for get/set/remove cookie

name: cookie name.
用法: 在头标签中,包括以下代码:

<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.js"></script>
范例

if ( cookie.isEnabled() )
    console.log('cookie is enabled on your browser');
else
    console.error('cookie is disabled on your browser');
cookie.set('age', 25);
cookie.set(名称、值) 放一块饼干

name: cookie name.
value: cookie value.
name: cookie name.
defaultValue: cookie default value. Default is undefined.
returns cookie value or defaultValue if cookie was not found
范例

if ( cookie.isEnabled() )
    console.log('cookie is enabled on your browser');
else
    console.error('cookie is disabled on your browser');
cookie.set('age', 25);
get(name[,defaultValue]); 买块饼干

name: cookie name.
value: cookie value.
name: cookie name.
defaultValue: cookie default value. Default is undefined.
returns cookie value or defaultValue if cookie was not found
例子 cookie.remove(名称); 移除cookie

name: cookie name.
例子 简单的阅读

var getCookie = function (name) {
    var valueStart = document.cookie.indexOf(name + "=") + name.length + 1;
    var valueEnd = document.cookie.indexOf(";", valueStart); 
    return document.cookie.slice(valueStart, valueEnd)
}

我使用了以下函数,这些函数是我从各种来源中找到的最好的函数,并剔除了一些bug或差异