在javascript中显示cookie值

时间:2015-01-19 08:34:41

标签: javascript

我一直在尝试在javascript中显示Cookie值。我想提醒输入框中的用户输入为cookie值。 我的代码如下;

<body>
<script>
function WriteCookie(){
    if(document.myform.customer.value=""){
        alert("Write something in the text input.");
        return;
    }

    var cookievalue=escape(document.myform.customer.value) + ";";
    document.cookie="name=" + cookievalue;
    alert("Setting cookie:" + "name=" + cookievalue);

}
</script>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>

</body>

在此示例中,每当用户单击该按钮时,都会调用WriteCookie()。此函数检查输入是否为空。如果不是emplty,它试图抓取文本并将其存储在cookievalue变量中.Escape函数然后使文本输入随着&#34;;&#34;附加到字符串的末尾。现在,然后我用document.cookie函数设置cookie。当我在下一步中使用cookie时,cookie不会显示出来。 Plz出了什么问题?

1 个答案:

答案 0 :(得分:0)

试试这个: -

 <body>
<script>
    function WriteCookie(){
    if(document.myform.customer.value==""){
        alert("Write something in the text input.");
        return;
        }

    alert(document.cookie);

            var cookievalue=escape(document.myform.customer.value) + ";";
            document.cookie="name=" + cookievalue;
            alert("Setting cookie:" + "name=" + cookievalue);

        }
</script>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>

</body>
相关问题