使用 jQuery 创建、读取和删除 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1599287/
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-26 11:48:32  来源:igfitidea点击:

Create, read, and erase cookies with jQuery

jquerycookies

提问by Agus Puryanto

Somebody help me. How to create, read and erase some cookies with jQuery ?

来人帮帮我。如何使用 jQuery 创建、读取和删除一些 cookie?

回答by Ramesh Soni

Use COOKIE plugin:

使用COOKIE 插件

Set a cookie

设置一个 cookie

$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
$.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie

得到一块饼干

alert( $.cookie("example") );

Delete the cookie

删除cookie

$.removeCookie("example");

回答by balexandre

As I know, there is no direct support, but you can use plain-ol' javascript for that:

据我所知,没有直接支持,但您可以使用普通 ol' javascript:

        // 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 eraseCookie(name) {
            createCookie(name, "", -1);
        }

回答by louis_coetzee

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

使用 jquery cookie 插件,链接为今天工作:https: //github.com/js-cookie/js-cookie