【问题标题】:Set cookie to expire in 24 hours将 cookie 设置为 24 小时后过期
【发布时间】:2012-10-18 19:05:12
【问题描述】:

一个表单有如下代码来防止多个表单提交:

function AllowNoDups() { var cookie_ls = document.cookie; if (cookie_ls.indexOf(document.location) > -1) {
  alert("You've already submitted a free meter request. Thank you for your interest!  ");
  return false; } else { document.cookie = 'username=' + value; + 'expires=' + var now = new Date(); var time = now.getTime(); time += 3600 * 1000; now.setTime(time); document.cookie = 'username=' + value + '; expires=' + now.toGMTString() + '; path=/';; + 'path = /' document.cookie =  "; path=/newform.php; expires=Sun, 1-Jan-2040 00:00:01 GMT;"; return true;};};

虽然代码有效,但我宁愿将 cookie 设置为 24 小时后过期,而不是指定 cookie 过期的日期。我将如何实现这一目标?谢谢!

【问题讨论】:

  • 是什么阻止我清除我的 cookie 并再次提交?我的意思是,如果你还没有这样做,请确保你也检查服务器端。
  • 更改时间 += 3600 * 1000;到时间 += (24*60*60*1000)

标签: javascript setcookie


【解决方案1】:

您可以使用max-age 属性。请参阅此维基百科article

作为将 cookie 过期设置为绝对过期的替代方法 日期/时间,RFC 6265 允许使用 Max-Age 属性来设置 cookie 的过期时间为未来几秒的间隔,相对 到浏览器收到 cookie 的时间。

【讨论】:

  • 不幸的是,IE 6,7,8 不支持 max-age 属性,因为它占用户群的 80% 以上,所以它不是我可以部署的真正解决方案。不过感谢您的及时回复!
  • 现在确实可以作为解决方案,因为 IE 6、7、8 现在已弃用。
【解决方案2】:

使用此函数并根据您的要求传递参数..

function callcookie(name,value,days){
  if(days){
      var d=new Date();
      d.setTime(d.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+d.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2023-02-01
    • 1970-01-01
    • 2011-03-18
    相关资源
    最近更新 更多