【问题标题】:How to set cookie's expire date with js?js如何设置cookie的过期时间?
【发布时间】:2019-10-30 21:04:34
【问题描述】:

这是我的脚本。

<script>
        function save() {
            var x=document.getElementById("user").value;
            var y=document.getElementById("password").value;
            document.cookie=x+" "+y;
        }
        function write() {
            document.write(document.cookie);
        }
</script>

这很好用,它会记住 var x 和 y 的值,并在调用函数 write() 时写入它们。当我关闭浏览器时,cookie 会被删除,这是理所当然的。但我想设置一年的到期日期;我尝试了很多方法,但我真的无法让它发挥作用。有什么帮助吗?

【问题讨论】:

标签: javascript html cookies


【解决方案1】:

添加一个 max-age 段:

 ;max-age=<max-age-in-seconds>

Documentation here

这将使您的 cookie 在一天内过期:

    function save() {
        var x=document.getElementById("user").value;
        var y=document.getElementById("password").value;
        document.cookie=x+"="+y+";max-age="+(3600*24);
    }

我建议使用库来设置 cookie,因为在跨浏览器设置/读取 cookie 时有很多陷阱。 For example the js-cookie library.

注意:将明文密码存储在 cookie 中是不好的做法。您可能正在寻找会话 cookie。

【讨论】:

    【解决方案2】:

    这是来自w3schools 的示例。

    document.cookie="cookiename=cookievalue; expires=Thu, 18 Dec 2013 12:00:00 UTC";
    

    【讨论】:

      【解决方案3】:

      你只需要写

      document.cookie = "cookiename=value; expires= 03 Dec 2015 00:00"
      

      但是,如果您只是在 Google 上输入“javascript cookies”,您可以找到此页面:http://www.w3schools.com/js/js_cookies.asp 它非常有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        • 1970-01-01
        相关资源
        最近更新 更多