【问题标题】:Saving Cookie with Javascript用 Javascript 保存 Cookie
【发布时间】:2018-09-25 10:02:57
【问题描述】:

希望创建一个 cookie,其中包含希望参加测验的人的姓名。

它会在页面加载时询问用户,但当我重新加载浏览器时它不记得 cookie。

有人知道为什么吗?

抱歉,我知道这是一个非常基本的问题。尝试用 Javascript 自学 cookie。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
<style>
h1, h2{
    margin-top: 150px;
    text-align: center;
    font-family: Arial, Helvetica, sans-serif;
}
p {
    margin-bottom:0px;
    text-align: center;
}
.button {
    padding: 20px 20px;
    border-radius: 15px;
    font-size: 14px;
    cursor: pointer;
    margin-left: 100px;
    margin-top: 50px;

}
#banner{
     padding:0 145px;
}
#banner img{
     display:block;
     margin:0 auto;
}
div.buttonGroup{
    margin-left: 450px;
}
body {
    background-color:#ffdab3;
}
</style>
<meta charset="UTF-8">
</head>

<body onload checkCookies()>

<script>
function setCookie(cname, cvalue, exdays) {

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

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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 user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}
</script>
</body>
</html>

【问题讨论】:

  • 你加载的页面是http://还是file:///
  • @raul.vila 我正在使用 file:// 加载它,这是一个问题吗?
  • @raul.vila 我已将它保存到我的 xampp 位置的 htdocs 文件夹中,因此尝试使用本地主机并且它有效!尽管感谢您的帮助,但我将对差异进行一些研究!如果您想将其写为答案,我可以将其选为正确的。

标签: javascript html css cookies


【解决方案1】:

@raul.vila 不要以静态方式加载页面(尝试使用本地服务器)。这样就可以了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2019-02-11
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多