Javascript不会保存cookie

时间:2015-03-09 12:16:00

标签: javascript cookies

我正在使用快速的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检查从布尔检查更改为字符串后,没有任何区别。

2 个答案:

答案 0 :(得分:1)

可能正在保存cookie。但是你的getCookie方法在6 c.substring(name,length,c.length);

上有一个拼写错误

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

更新

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

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

OR

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

答案 1 :(得分:0)

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

相关问题