如何使用 JavaScript 设置和获取 Cookie?


设置 Cookie

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

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

这里,“expires” 属性是可选的。如果使用有效日期或时间提供此属性,则 Cookie 将在给定日期或时间过期,此后将无法访问 Cookie 的值。

示例

尝试以下操作。它在输入 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>

获取 Cookie

读取 Cookie 与写入 Cookie 一样简单,因为 document.cookie 对象的值就是 Cookie。因此,您可以随时使用此字符串访问 Cookie。document.cookie 字符串将保留一个用分号分隔的名称=值对列表,其中名称是 Cookie 的名称,值是其字符串值。

示例

您可以尝试运行以下代码来读取 Cookie:

在线演示

<html>
   <head>
      <script>
         <!--
            function ReadCookie() {
               var allcookies = document.cookie;
               document.write ("All Cookies : " + allcookies );
               // Get all the cookies pairs in an array
               cookiearray = allcookies.split(';');
               // Now take key value pair out of this array
               for(var i=0; i<cookiearray.length; i++) {
                  name = cookiearray[i].split('=')[0];
                  value = cookiearray[i].split('=')[1];
                  document.write ("Key is : " + name + " and Value is : " + value);
               }
            }
         //-->
      </script>
   </head>
   <body>
      <form name="myform" action="">
         <p> click the following button and see the result:</p>
         <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
      </form>
   </body>
</html>

更新于: 2020年6月16日

3K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.