Javascript Cookie未存储

时间:2016-09-30 14:07:58

标签: javascript html

我尝试创建一个Javascript cookie,我在其中创建cookie并将其存储在浏览器中,并检查cookie是否存储在浏览器中。如果cookie存储在浏览器上,它将返回欢迎用户用户名,否则它将要求用户输入他的名字。

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

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 user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}			
<body onload= "checkCookie()">
<input type= "button" onclick= "checkCookie()" value= "val"/>
</body>

此代码会一次又一次地提示输入cookie,但不会将cookie存储在浏览器中 请看看这个并找到解决这个问题的方法? 感谢

0 个答案:

没有答案