最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set cookie to expire in 24 hours - Stack Overflow

programmeradmin3浏览0评论

A form has the following code to prevent multiple form submissions:

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

While the code works, I would rather set the cookie to expire after 24 hours have elapsed, as opposed to specifying a date at which the cookie would expire. How would I go about acplishing this? Thank you!

A form has the following code to prevent multiple form submissions:

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

While the code works, I would rather set the cookie to expire after 24 hours have elapsed, as opposed to specifying a date at which the cookie would expire. How would I go about acplishing this? Thank you!

Share Improve this question asked Oct 18, 2012 at 19:05 user1736377user1736377 311 gold badge1 silver badge2 bronze badges 2
  • 1 What's to stop me from clearing my cookies and submitting again? My point is, make sure you do this check server-side as well if you aren't already. – TheZ Commented Oct 18, 2012 at 19:06
  • Change time += 3600 * 1000; to time += (24*60*60*1000) – mplungjan Commented Oct 18, 2012 at 19:11
Add a ment  | 

2 Answers 2

Reset to default 2

You can use the max-age attribute. See this wikipedia article.

As an alternative to setting cookie expiration as an absolute date/time, RFC 6265 allows the use of the Max-Age attribute to set the cookie’s expiration as an interval of seconds in the future, relative to the time the browser received the cookie.

Use this function and pass the parameter as per your requirement..

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=/";
}
发布评论

评论列表(0)

  1. 暂无评论