简体   繁体   English

设置 cookie 不适用于 Javascript 或 jQuery

[英]Set cookie not working with Javascript or jQuery

my problem is that to set a cookie by click on a button is not working.我的问题是通过单击按钮设置 cookie 不起作用。 I've tested it on 3 different ways.我已经用 3 种不同的方式对其进行了测试。

HTML: HTML:

<!DOCTYPE html>
<html dir="ltr">
    <head> [...]
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
        <script src="/cookies/js/jquery.cookie.js"></script>
        <script>
            document.getElementById('btnSetCookie').onclick = function () {
                $.cookie('cookie-1', 'true');
                alert('You have set the cookie: ' + jQuery.cookie('cookie-1'));
            });
            $(function () {
                $("#btnSetCookie").click(function () {
                    jQuery.cookie('cookie-2', 'true');
                    alert('You have set the cookie: ' + jQuery.cookie('cookie-2'));
                });
            });
            $(document).ready(function () {
                $("#btnSetCookie").on('click', function () {
                    $.cookie('cookie-3', 'true');
                    alert('You have set the cookie: ' + jQuery.cookie('cookie-3'));
                });
            });
        </script>
    </head>
    <body> [...]
        <button id="btnSetCookie">set cookie</button> [...]
    </body>
</html>

Any idea what's my mistake?知道我的错误是什么吗?

The reason this is not working for you is that you cannot set cookies if you're not running on a server.这对您不起作用的原因是,如果您不在服务器上运行,则无法设置 cookie。 In other words, if you're serving the file in a browser locally using file://, it simply won't work.换句话说,如果您使用 file:// 在本地浏览器中提供文件,它根本无法工作。

Both your second and third option run fine.您的第二个和第三个选项都运行良好。 I would clean them both up and use either $ or jQuery consistently, but both work when running on a server.我会清理它们并始终如一地使用 $ 或 jQuery,但两者都在服务器上运行时工作。

Here's a demo of your code working.这是您的代码工作的演示

$(document).ready(function () {
  $("#btnSetCookie").on('click', function () {
    $.cookie('cookie-3', 'true');
    alert('You have set the cookie: ' + $.cookie('cookie-3'));
  });
});

You could also consider using a more up-to-date version of jQuery, as well as the plugin you're using (the version you're using is no longer maintained).您还可以考虑使用更新版本的 jQuery,以及您正在使用的插件(您正在使用的版本不再维护)。 In fact, the newer version of the plugin is no longer dependent upon jQuery at all.事实上,新版本的插件根本不再依赖于 jQuery。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM