如何在JavaScript中创建Cookie?

使用Cookie是记住和跟踪偏好,购买,佣金和其他信息(以获得更好的访问者体验或站点统计信息)所需的最有效方法。

创建cookie的最简单方法是将一个字符串值分配给document.cookie对象,如下所示。

document.cookie = "key1=value1;key2=value2;expires=date";

这里的expires属性是可选的。如果为该属性提供有效的日期或时间,则cookie将在给定的日期或时间到期,此后,将无法访问cookie的值。

注意-Cookie值不能包含分号,逗号或空格。因此,您可能要使用JavaScriptescape()函数对值进行编码,然后再将其存储在cookie中。如果这样做,则unescape()在读取Cookie值时还必须使用相应的函数。

示例

您可以尝试运行以下代码。它在输入cookie中设置客户名称。

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("输入一些值!");
                  return;
               }
               cookievalue= escape(document.myform.customer.value) + ";";
               document.cookie = "name = " + cookievalue;
               document.write ("Setting Cookies : " + "name = " + cookievalue );
            }
         //-->
      </script>
   </head>
   <body>
      <form name = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
      </form>
   </body>
</html>