如何在 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 字串將保留以分號分隔的 name=value 對列表,其中 name 是 Cookie 的名稱,value 是其字串值。

示例

您可以嘗試執行以下程式碼來讀取 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日

瀏覽量:128

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.