JavaScript Cookie不保存

时间:2017-12-28 08:33:03

标签: javascript

我遇到了JavaScript Cookie问题。我上次运行这个代码,它就像我想要的那样工作。它会显示一条提示,让我输入我的姓名,输入我的姓名后点击“确定”。当我刷新页面并显示一条警告消息时,它也起作用了。再次欢迎Mark"。     但是现在,这段代码不再起作用了。它每次刷新页面时都只询问并询问我的名字。我怀疑它是否在我的浏览器上我已经尝试在IE,Firefox,Chrome和MS Edge中使用此代码,但它也做同样的事情。希望你能解决问题的人。谢谢。代码如下:

<html>
  <head>
    <script type="text/javascript">
      function setCookie(cname, cvalue, exdays)
      {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toGMTString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
      }
      function getCookie(cname)
      {
        var name = cname + "=";
        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);
          }
          if(c.indexOf(name) == 0)
          {
            return c.substring(name.length,c.length);
          }
        }
        return "";
      }
      function checkCookie()
      {
        var username = getCookie("username");
        if(username != null && username != "")
        {
          alert("Welcome again " + username);
        } else
        {
          username = prompt("Please enter your name:" , "");
          if(username != null && username != "")
          {
            setCookie("username" , username , 365);
          }
        }
      }
   </script>
 </head>
 <body onload="checkCookie()">
 </body>
 </html>

2 个答案:

答案 0 :(得分:1)

var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 
1000));
var expires = "expires=";
document.cookie = cname + "=" + cvalue + "; " + 
expires;

您的Cookie字符串不包含日期。你忘记了+ d

答案 1 :(得分:0)

您的问题可能就在这一行:

document.cookie = cname + "=" + cvalue + "; " +
            expires;

您忘了添加日期:

document.cookie = cname + "=" + cvalue + "; " +
            expires + d;