未设置 JavaScript Cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8097423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:15:46  来源:igfitidea点击:

JavaScript Cookies are not being set

javascriptcookies

提问by Seth

I followed went through some related threads and also followed the tutorial on http://www.quirksmode.org/js/cookies.htmlbut I can't get my cookie to set.

我遵循了一些相关的线程,也遵循了http://www.quirksmode.org/js/cookies.html上的教程,但我无法设置我的 cookie。

<script type="text/javascript">
function setcookie(name, value, days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+days*24*60*60*1000));
        var expires = "; expires="date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="value+expires+;path=/";
}
</script>

Then in my tag I have:

然后在我的标签中,我有:

<body>
<script type="text/javascript">
    setcookie("testcookie", "test", 1);
</script>
</body>

Any ideas where I'm going wrong? I have cookies enabled, using FF and I can see cookies being created in real time by sites like Youtube but this one won't set at all.

任何想法我哪里出错了?我启用了 cookie,使用 FF,我可以看到 Youtube 等网站实时创建 cookie,但这个根本不会设置。

回答by Yogu

The script contains several mistakes. Here's the corrected version (tested):

该脚本包含几个错误。这是更正后的版本(已测试):

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

回答by jfriend00

You are missing a + sign and a quote mark on this line:

您在此行上缺少 + 号和引号:

document.cookie = name+"="value+expires+;path=/";

should be:

应该:

document.cookie = name + "=" + value + expires + ";path=/";

I'd suggest you look in your browser's error console or your javascript debugger's console to see javascript errors.

我建议您查看浏览器的错误控制台或 javascript 调试器的控制台以查看 javascript 错误。