如何使用jQuery设置/取消设置cookie?

How do I set/unset a cookie with jQuery?

提问人:omg 提问时间:9/22/2009 最后编辑:Kamil Kiełczewskiomg 更新时间:9/30/2022 访问量:1483626

问:

如何使用 jQuery 设置和取消设置 cookie,例如创建一个名为 的 cookie 并将值设置为 ?test1

JavaScript jQuery DOM Cookie

评论


答:

1880赞 Alistair Evans 9/22/2009 #1

更新于 2019 年 4 月

cookie 读取/操作不需要 jQuery,因此不要使用下面的原始答案。

转到 https://github.com/js-cookie/js-cookie,并使用不依赖于 jQuery 的库。

基本示例:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

有关详细信息,请参阅 github 上的文档。


2019年4月前(旧)

查看插件:

https://github.com/carhartl/jquery-cookie

然后,您可以执行以下操作:

$.cookie("test", 1);

要删除:

$.removeCookie("test");

此外,要在 cookie 上设置一定天数(此处为 10 天)的超时:

$.cookie("test", 1, { expires : 10 });

如果省略 expires 选项,则 cookie 将成为会话 cookie,并在浏览器退出时被删除。

要涵盖所有选项,请执行以下操作:

$.cookie("test", 1, {
   expires : 10,           // Expires in 10 days

   path    : '/',          // The value of the path attribute of the cookie
                           // (Default: path of page that created the cookie).

   domain  : 'jquery.com', // The value of the domain attribute of the cookie
                           // (Default: domain of page that created the cookie).

   secure  : true          // If set to true the secure attribute of the cookie
                           // will be set and the cookie transmission will
                           // require a secure protocol (defaults to false).
});

要读回 cookie 的值,请执行以下操作:

var cookieValue = $.cookie("test");

更新(2015 年 4 月):

如下面的评论所述,开发原始插件的团队已经删除了新项目 (https://github.com/js-cookie/js-cookie) 中的 jQuery 依赖项,该项目具有与 jQuery 版本相同的功能和通用语法。显然,原始插件不会去任何地方。

评论

1赞 bogdan 1/7/2013
从更新日志中:“$.removeCookie('foo') 用于删除 cookie,使用 $.cookie('foo', null) 现已弃用”
74赞 Andrei Cristian Prodan 7/2/2013
@Kazar我花了 6 个小时,没有休息。今天早上我终于意识到了这个问题。我正在将它与 phonegap 一起使用,在网站上它可以毫无问题地工作,但在设备上,当您尝试检索具有 JSON 的 cookie 时,它已经是一个对象,因此如果您尝试 JSON.parse 它,它将给出 JSON 解析错误。用“if typeof x == 'string'”解决了它,做JSON.parse,否则,只使用对象。6 该死的小时在所有错误的地方寻找错误
13赞 LessQuesar 8/10/2013
删除 Cookie 时,请确保还将路径设置为与最初设置 Cookie 相同的路径:$.removeCookie('nameofcookie', { path: '/' });
34赞 Fagner Brack 4/22/2015
现在是 2015 年,仅从这个答案来看,我们每周仍然在 jquery-cookie 存储库中收到超过 2k 的独立点击。我们可以从中学到几件事:1. 饼干不会很快消亡,2.人们仍然在谷歌上搜索“jquery插件来拯救世界”。jQuery对于处理cookie不是必需的,jquery-cookie被重命名为js-cookie(github.com/js-cookie/js-cookie),jquery依赖项在1.5.0版本中是可选的。将有一个 2.0.0 版本,其中包含很多有趣的东西,值得一看并做出贡献,谢谢!
2赞 Fagner Brack 4/23/2015
@Kazar 我们不打算实际移动它,该 URL 有相当多的总流量来自多个来源,Klaus 是“jquery-cookie”命名空间的历史所有者。无需担心该 URL 会很快消失。但是,我仍然鼓励大家开始关注新存储库的更新。
19赞 user177016 9/22/2009 #2

您可以使用此处提供的插件。

https://plugins.jquery.com/cookie/

然后写一个cookie做$.cookie("test", 1);

要访问设置的 cookie,请执行$.cookie("test");

评论

3赞 Andrei Cristian Prodan 7/2/2013
该插件有一个更新版本
449赞 Russ Cam 9/22/2009 #3

没有必要特别使用jQuery来操作cookie。

QuirksMode(包括转义字符)

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 = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(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 decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}

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

看一看

评论

2赞 Svetoslav Marinov 1/18/2011
嗨,Russ,jquery cookie 的好处是它可以转义数据
2赞 Russ Cam 1/19/2011
@lordspace - 只需将值包装在 window.escape/unescape 中即可分别写入/检索 cookie 值:)
47赞 SDC 7/11/2012
可以在此处找到更好的 cookie 代码:developer.mozilla.org/en/DOM/document.cookie
5赞 brauliobo 6/1/2014
jQuery cookie插件要简单得多
1赞 Rodislav Moldovan 10/26/2014
您可以使用 encodeURI 或 decodeURI 代替 escape 或取消转义
7赞 Webpixstudio 8/7/2013 #4

在浏览器中设置cookie的简单示例:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

只需复制/粘贴并使用此代码来设置您的cookie。

评论

1赞 Fagner Brack 4/22/2015
请注意,浏览器默认根据文件名缓存资源。在此示例中,当文件名更新为 时,将为所有人重新加载,否则浏览器根本不会向服务器发出请求以检查更新的内容。如果您在不更改文件名的情况下更新内部代码,则可能不会在已缓存资源的浏览器中重新加载它。jquery-1.9.0.min.jsjquery-1.9.1.min.jsjquery.cookie.jsjquery.cookie.js
0赞 Fagner Brack 4/22/2015
如果您正在编写一个网站并复制/粘贴它,请注意,如果您在不更改文件名的情况下更新版本,这将不起作用(除非您的服务器使用 E-Tags 处理缓存)。jquery.cookie.js
0赞 Mohammad Javad 6/21/2018
if ($.cookie('cookieStore')) { var data=JSON.parse($.cookie(“cookieStore”)); // 在不同页面中加载页面时找不到 $('#name').text(data[0]); $('#address').text(data[1]); }
186赞 Vignesh Pichamani 9/6/2013 #5
<script type="text/javascript">
    function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }

</script>

您可以将 cookie 设置为

setCookie('test','1','1'); //(key,value,expiry in days)

您可以像这样获得 cookie

getCookie('test');

最后,您可以像这样擦除 cookie

eraseCookie('test');

希望它能对某人有所帮助:)

编辑:

如果要将 cookie 设置为所有路径/页面/目录,请将 path 属性设置为 cookie

function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

谢谢 维 琪

评论

1赞 Vignesh Pichamani 10/1/2013
60 * 1000 = 60 秒 60* (60 * 1000) = 60 分钟,即 1 小时 24* (60* (60 * 1000)) = 1 天,其中 24 小时希望对您有所帮助。
1赞 Vignesh Pichamani 10/1/2013
1 * 24 * 60 * 60 * 1000 定制 1 个 1 天或可以做 365
1赞 Dss 4/24/2014
良好的功能...但是,为什么它们会出现在 document.ready 标签中呢?
1赞 Fagner Brack 4/22/2015
这在 Safari 或 IE 中不适用于 ASCII 范围之外的任何字符,例如 、 等。此外,这不适用于 cookie-name 或 cookie-value 中不允许的某些特殊字符。我推荐以下参考:tools.ietf.org/html/rfc6265é
2赞 Kolawole Emmanuel Izzy 3/8/2021
最好的答案
10赞 user890332 9/1/2014 #6

确保不要做这样的事情:

var a = $.cookie("cart").split(",");

然后,如果 cookie 不存在,调试器将返回一些无用的消息,例如“.cookie 不是函数”。

始终先声明,然后在检查 null 后进行拆分。喜欢这个:

var a = $.cookie("cart");
if (a != null) {
    var aa = a.split(",");

评论

0赞 Peter Mortensen 1/8/2018
示例代码不完整。是只缺少一个代码,还是缺少几行代码?}
0赞 user890332 1/10/2018
它只是缺少一个 },但显然您需要添加更多代码行才能继续您想要对拆分执行的操作。
3赞 barmyman 6/3/2015 #7

我认为 Fresher 给了我们很好的方法,但有一个错误:

    <script type="text/javascript">
        function setCookie(key, value) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (value * 24 * 60 * 60 * 1000));
            document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }
   </script>

你应该在 getTime() 附近添加 “value”;否则,cookie将立即过期:)

评论

2赞 Peter 6/4/2015
“value”可以是一个字符串。在问题中,他以 1 为例。值应为键等于的值,而不是 Cookie 过期前的天数。如果值作为“foo”传入,则您的版本将崩溃。
5赞 Moustafa Samir 8/10/2015 #8

您可以在此处使用Mozilla网站上的库

您将能够设置和获取这样的 cookie

docCookies.setItem(name, value);
docCookies.getItem(name);
14赞 seanjacob 10/26/2016 #9

这是我使用的全局模块 -

var Cookie = {   

   Create: function (name, value, days) {

       var expires = "";

        if (days) {
           var date = new Date();
           date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
           expires = "; expires=" + date.toGMTString();
       }

       document.cookie = name + "=" + value + expires + "; path=/";
   },

   Read: function (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;
    },

    Erase: function (name) {

        Cookie.create(name, "", -1);
    }

};
9赞 S1awek 3/9/2018 #10

以下是使用 JavaScript 设置 cookie 的方法:

以下代码取自 https://www.w3schools.com/js/js_cookies.asp

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

现在,您可以使用以下功能获取cookie:

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

最后,这是您检查cookie的方式:

function checkCookie() {
    var username = getCookie("username");
    if (username != "") {
        alert("Welcome again " + username);
    } else {
        username = prompt("Please enter your name:", "");
        if (username != "" && username != null) {
            setCookie("username", username, 365);
        }
    }
}

如果要删除 cookie,只需将 expires 参数设置为传递的日期:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
1赞 Colin R. Turner 7/3/2018 #11

我认为 Vignesh Pichamani 的答案是最简单、最干净的。只是增加了他设置到期前天数的能力:

编辑:如果未设置日期数,还添加了“永不过期”选项

        function setCookie(key, value, days) {
            var expires = new Date();
            if (days) {
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
            } else {
                document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
            }
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

设置 cookie:

setCookie('myData', 1, 30); // myData=1 for 30 days. 
setCookie('myData', 1); // myData=1 'forever' (until the year 9999) 
1赞 Hasan Badshah 8/10/2018 #12

如何使用它?

//To set a cookie
$.cookie('the_cookie', 'the_value');

//Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });

//Create expiring cookie, valid across entire page:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });

//Read cookie
$.cookie('the_cookie'); // => 'the_value'
$.cookie('not_existing'); // => null

//Delete cookie by passing null as value:
$.cookie('the_cookie', null);

// Creating cookie with all availabl options
$.cookie('myCookie2', 'myValue2', { expires: 7, path: '/', domain: 'example.com', 
         secure: true, raw: true });

可用选项

expires:定义 Cookie 的生存期。值可以是 Number(将解释为创建后的天数)或 Date 对象。如果省略,则 cookie 是会话 cookie。

path:定义 cookie 有效的路径。默认情况下,Cookie 的路径是创建 Cookie 的页面的路径(标准浏览器行为)。例如,如果要使其在整个页面上可用,请使用路径:“/”。

domain:创建 Cookie 的页面的域。

secure:默认值:false。如果为 true,则 cookie 传输需要安全协议 (https)。

raw:默认情况下,在创建/读取时,使用 encodeURIComponent/decodeURIComponent 对 cookie 进行编码/解码。通过设置 raw: true 关闭。

1赞 Fabian 7/3/2019 #13

我知道有很多很好的答案。通常,我只需要读取 cookie,我不想通过加载额外的库或定义函数来产生开销。

以下是如何在一行 javascript 中读取 cookie。我在 Guilherme Rodrigues 的博客文章中找到了答案:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

这读作名为 , nice, clean and simple 的 cookie。key

1赞 Kamil Kiełczewski 7/1/2020 #14

尝试(此处为文档,SO 代码片段不起作用,因此运行此代码片段)

document.cookie = "test=1"             // set
document.cookie = "test=1;max-age=0"   // unset
0赞 Slavik Meltser 3/19/2021 #15

以下代码将删除当前域和所有尾随子域(、、等)中的所有 cookie。www.some.sub.domain.com.some.sub.domain.com.sub.domain.com

单行原版JS版本(无需jQuery):

document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));

这是此单行的可读版本:

document.cookie.replace(
  /(?<=^|;).+?(?=\=|;|$)/g, 
  name => location.hostname
    .split(/\.(?=[^\.]+\.)/)
    .reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
    .map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);
0赞 ruffin 6/17/2021 #16

我知道,已经有很多答案了,但这里有一个已经设置获取删除了所有精美的香草,并很好地放入全局参考中:

window.cookieMonster = window.cookieMonster || 
    {
        // https://stackoverflow.com/a/25490531/1028230
        get: function (cookieName) {
            var b = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
            return b ? b.pop() : '';
        },

        delete: function (name) {
            document.cookie = '{0}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
                .replace('{0}', name);
        },

        set: function (name, value) {
            document.cookie =
                '{0}={1};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax'
                .replace('{0}', name)
                .replace('{1}', value);
        }
    };

请注意,cookie 获取正则表达式是从另一个城堡中一个问题的答案中获取的。


让我们测试一下:

cookieMonster.set('chocolate', 'yes please');
cookieMonster.set('sugar', 'that too');

console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);

cookieMonster.delete('chocolate');

console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);

如果您在尝试之前没有任何饼干,应该给您...

yes please
chocolate=yes please; sugar=that too

sugar=that too

请注意,饼干的持续时间并不长,但从我们的角度来看,本质上是这样。您可以通过查看此处的字符串或其他答案来轻松更改日期。

2赞 Kai 1/8/2022 #17

与以前的答案相比,减少了操作次数,我使用以下方法。

function setCookie(name, value, expiry) {
    let d = new Date();
    d.setTime(d.getTime() + (expiry*86400000));
    document.cookie = name + "=" + value + ";" + "expires=" + d.toUTCString() + ";path=/";
}

function getCookie(name) {
    let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return cookie ? cookie[2] : null;
}

function eatCookie(name) {
    setCookie(name, "", -1);
}
2赞 samnoon 9/30/2022 #18

背景

Cookie 最初是由 Netscape 发明的,用于为 Web 服务器和浏览器提供“内存”。HTTP协议是无状态的,该协议安排将网页传输到您的浏览器,并将页面请求发送到服务器,这意味着一旦服务器将页面发送到请求它的浏览器,它就不会记住任何事情。因此,如果您第二次、第三次、第一百次或第一百万次访问同一网页,服务器会再次将其视为您第一次访问该网页。

这在很多方面都可能很烦人。当您要访问受保护的页面时,服务器无法记住您是否标识了自己,它无法记住您的用户首选项,它无法记住任何内容。一旦个性化被发明出来,这就成为一个主要问题。

饼干就是为了解决这个问题而发明的。还有其他方法可以解决这个问题,但 cookie 易于维护且用途广泛。

Cookie 的工作原理

Cookie 只不过是存储在浏览器中的一个小文本文件。它包含一些数据:

  • 包含实际数据的名称/值对
  • 到期日后不再有效
  • 应发送到的服务器的域和路径

要使用 Javascript 设置或取消设置 Cookie,您可以执行以下操作:

// Cookies
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 setCookie(name, days) {
    createCookie(name, name, days);
}
function unsetCookie(name) {
    createCookie(name, "", -1);
}

您可以像下面这样访问,

setCookie("demo", 1); // to set new cookie

readCookie("demo"); // to retrive data from cookie

unsetCookie("demo"); // will unset that cookie