如何在 JavaScript 中创建 cookie?

javascriptweb developmentfront end technology

使用 cookie 是记住和跟踪偏好、购买、佣金以及改善访客体验或网站统计所需的其他信息的最有效方法。

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

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

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

注意 − Cookie 值不得包含分号、逗号或空格。因此,您可能希望在将值存储在 cookie 中之前使用 JavaScript escape() 函数对其进行编码。如果这样做,在读取 cookie 值时,您还必须使用相应的 unescape() 函数。

示例

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

<html>
   <head>
      <script>
         <!--
            function WriteCookie() {
               if( document.myform.customer.value == "" ) {
                  alert("Enter some value!");
                  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>

相关文章


有用资源