Javascript 不会保存 cookie

Javascript won't save cookie

本文关键字:cookie 保存 Javascript      更新时间:2023-09-26

我正在使用快速的Javascript代码(基于教程)来尝试在网站上创建年龄屏幕。但是,尽管年龄屏幕应该只弹出一次,然后在一段时间内正常,但它每次刷新都会弹出。这是我使用的代码:

<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 age = getCookie("allowed");
    if (age != true) {
        age = confirm("you must be 18 or older to enter and view the content on this blog");
    }
    if (age == true) {
        setCookie("allowed", age, 7);
    } else if (age == false) {
        //window.location.replace("http://tumblr.com/dashboard");
    }
    return age;
}
</script>

我已经检查了我能找到的所有可用的在线资源和教程,但没有任何解释为什么这不会正确保存 cookie。如果我打开控制台,它会识别创建 cookie 的站点,但会为我提供所有内容的未定义值。

如果我让控制台运行 checkCookie() 函数,它会根据我单击"确定"还是"取消"返回正确的值,但它仍然不会实际将该值保存到 cookie 中。

能想到这可能发生的任何原因?

更新

age == true检查从布尔检查更改为字符串后,没有任何区别。

cookie 可能正在保存。但是您的getCookie方法中有一个拼写错误,例如6 c.substring(name,length,c.length);

相反,你应该有c.substring(name.length,c.length);

更新

将 checkCookie 方法中的以下行更改为

if (age) {
    setCookie("allowed", age, 7);
}

if (age === true) {
    setCookie("allowed", age, 7);
}

调用 setCookie 后,刷新浏览器,您应该能够看到 cookie 集。

更新 2

getCookie 返回一个字符串,因此它应该age != "true"confirm返回一个布尔值,因此age === true应该可以工作

var age = getCookie("allowed");
if (age != "true") {
    age = confirm("you must be 18 or older to enter and view the content on this blog");
}
if (age === true) {
    setCookie("allowed", age, 7);
} else if (age == false) {
    //window.location.replace("http://tumblr.com/dashboard");
}

(typeof age) 是字符串因此,您可以将age != true更改为age != 'true',而对于其他检查也是如此,或者将其转换为布尔值,例如!!age != true