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

omg*_*omg 1209 javascript cookies jquery

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

Kaz*_*zar 1734

看插件:

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

然后你可以这样做:

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

// Read the cookie
Cookies.get('name') => // => 'value'
Run Code Online (Sandbox Code Playgroud)

删除:

$.cookie("test", 1);
Run Code Online (Sandbox Code Playgroud)

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

$.removeCookie("test");
Run Code Online (Sandbox Code Playgroud)

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

涵盖所有选项:

$.cookie("test", 1, { expires : 10 });
Run Code Online (Sandbox Code Playgroud)

要回读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).
});
Run Code Online (Sandbox Code Playgroud)

如果cookie是在与当前cookie不同的路径上创建的,您可能希望指定path参数:

var cookieValue = $.cookie("test");
Run Code Online (Sandbox Code Playgroud)

更新(2015年4月):

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

  • @Kazar我花了6个小时,没有休息.我今天早上终于意识到了这个问题.我正在使用phonegap,在网站上它没有问题,但在设备上,当你尝试检索具有JSON的cookie时,它已经是一个对象,所以如果你尝试JSON.parse它,它将给出JSON解析错误.使用"if typeof x =='string'"解决它做JSON.parse,否则,只需使用该对象.6个该死的小时在所有错误的地方寻找错误 (67认同)
  • 这是2015年,我们仍然在jquery-cookie存储库中每周收到超过2k的独特点击量.我们可以从中学到以下几点:1.cookie不会很快消失2.人们仍然谷歌搜索"jquery插件来拯救世界".jQuery不是处理cookie所必需的,jquery-cookie正在重命名为js-cookie(https://github.com/js-cookie/js-cookie),jquery依赖在1.5.0版本中是可选的.会有一个版本2.0.0,有很多有趣的东西,值得一看,贡献,谢谢! (28认同)
  • 删除cookie时,请确保将路径设置为与最初设置cookie相同的路径:`$ .removeCookie('nameofcookie',{path:'/'});` (9认同)
  • @Kazar我们不打算实际移动它,来自多个来源的URL有相当大的总流量,而Klaus是"jquery-cookie"命名空间的历史所有者.没有必要担心该URL很快就会消失.但是,我仍然鼓励大家开始观看新的存储库以获取更新. (2认同)

Rus*_*Cam 418

没有必要特别使用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);
}
Run Code Online (Sandbox Code Playgroud)

看一眼

  • 更好的cookie代码可以在这里找到:https://developer.mozilla.org/en/DOM/document.cookie (44认同)
  • jQuery cookie插件更简单 (3认同)
  • 你好Russ,关于jquery cookie的好处是它逃脱了数据 (2认同)
  • @lordspace - 只需将window.escape/unescape中的值包装成分别写入/检索cookie值:) (2认同)

Vig*_*ani 136

<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>
Run Code Online (Sandbox Code Playgroud)

您可以像设置cookie一样设置

setCookie('test','1','1'); //(key,value,expiry in days)
Run Code Online (Sandbox Code Playgroud)

你可以像这样获得cookies

getCookie('test');
Run Code Online (Sandbox Code Playgroud)

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

编辑:

如果你想单独为主页保存cookie的路径,那就这样做吧

eraseCookie('test');
Run Code Online (Sandbox Code Playgroud)

谢谢,薇薇

  • 最佳答案中的最佳答案 (2认同)

小智 17

你可以使用这里提供的插件..

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

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

访问设置cookie做 $.cookie("test");

  • 有一个更新版本的插件 (2认同)

sea*_*cob 12

这是我使用的全局模块 -

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

};
Run Code Online (Sandbox Code Playgroud)


use*_*332 9

确保不要做这样的事情:

var a = $.cookie("cart").split(",");
Run Code Online (Sandbox Code Playgroud)

然后,如果cookie不存在,调试器将返回一些无用的消息,如".cookie not a function".

始终先声明,然后在检查null后执行拆分.像这样:

var a = $.cookie("cart");
if (a != null) {
    var aa = a.split(",");
Run Code Online (Sandbox Code Playgroud)


小智 7

在浏览器中设置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>
Run Code Online (Sandbox Code Playgroud)

简单的只需复制/粘贴并使用此代码设置您的cookie.


S1a*_*wek 7

这是使用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=/";
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以使用以下功能获取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 "";
}
Run Code Online (Sandbox Code Playgroud)

最后,这是您检查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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Run Code Online (Sandbox Code Playgroud)


Mou*_*mir 5

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

你将能够设置并获得这样的cookie

docCookies.setItem(name, value);
docCookies.getItem(name);
Run Code Online (Sandbox Code Playgroud)