功能不会存储cookie

时间:2013-07-07 22:06:02

标签: javascript html cookies

我正在尝试创建然后在javascript中检索cookie。我正在使用谷歌浏览器,当我运行下面的代码时,它不会在页面重新加载后存储cookie。

以下是我的代码

   <html>
       <title> Cookies </title>
         <body onload="checkCookie()">
         <script type="text/javascript">

        function getCookie(c_name){
            var c_value = document.cookie;
            var c_start = c_value.indexOf(" " + c_name + "=");
            if (c_start == -1){
                c_start = c_value.indexOf(c_name + "=");
            }
            if (c_start == -1){
                c_value = null;
            }else{
                c_start = c_value.indexOf("=", c_start) + 1;
                var c_end = c.value.indexOf(";", c_start);

            if (c_end ==-1){
                c_end = c_value.lenth;
            }
            c_value = unescape(c_value.substring(c_start,c_end));
            }
            return c_value;
        }

        function setCookie(c_name,value,exdays){
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
            document.cookie=c_name + "=" + c_value;
        }

        function checkCookie(){
            var username = getCookie("username");
            if(username!=null && username!=""){
                alert("Welcome again " + username);
            }else{
                username=prompt("Please enter your name:","");
                if(username!=null && username!=""){
                    setCookie("username",username,365);
                    document.write(username);
                }


            }
        }

    </script>
<body>

我不确定为什么它不起作用,我可以从这里复制/粘贴http://www.w3schools.com/js/js_cookies.asp

1 个答案:

答案 0 :(得分:1)

这是一个有趣的调试程序。谢谢W3Schools。下次我建议您使用控制台和MDN

第一个很容易看到的错误是:

c_end = c_value.lenth; //

应该是:

c_end = c_value.length;//

如果您使用该代码,您会注意到控制台提醒c is not defined.

好的我们逐个运行该功能,我们看到在运行getCookie

时出现错误

好的检查!

function getCookie(){
//Weird use if getIndex
//Someone forgot about regex
//..
 c_end = c.value.length; // AHA!!!
}

应该是:

c_end = c_value.length;

至于你的其他问题

setCookie使用new date()表示到期,这意味着立即

使用:

function setCookie(c_name,value,exdays){
            var exdate = exdays;
/....
}

享受。