ES6 - Cookies

Web 浏览器和服务器使用 HTTP 协议进行通信。HTTP 是无状态协议,即它不会在客户端发出的多个请求中维护客户端的数据。客户端和服务器之间的完整请求-响应周期定义为 会话。Cookie 是浏览器用于存储与用户会话相关的数据的默认机制。

工作原理?

您的服务器以 cookie 的形式向访问者的浏览器发送一些数据。浏览器可能会接受该 cookie。如果接受,它将作为纯文本记录存储在访问者的硬盘上。现在,当访问者到达您网站上的另一个页面时,浏览器会将相同的 cookie 发送到服务器以供检索。一旦检索到,您的服务器就会知道/记住之前存储的内容。

Cookie 是 5 个可变长度字段的纯文本数据记录。

  • Expires − Cookie 的过期日期。如果为空,则 Cookie 将在访问者退出浏览器时过期。

  • Domain − 您网站的域名。

  • Path − 设置 Cookie 的目录或网页的路径。如果您想从任何目录或页面检索 Cookie,则可以为空。

  • Secure − 如果此字段包含单词"secure",则只能使用安全服务器检索 Cookie。如果此字段为空,则不存在此类限制。

  • 名称 = 值 − Cookie 以键值对的形式设置和检索。

Cookie 最初是为 CGI 编程设计的。Cookie 中包含的数据会自动在 Web 浏览器和 Web 服务器之间传输,因此服务器上的 CGI 脚本可以读取和写入存储在客户端的 Cookie 值。

JavaScript 还可以使用 Document 对象的 cookie 属性来操作 Cookie。JavaScript 可以读取、创建、修改和删除适用于当前网页的 Cookie。

存储 Cookie

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

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

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

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

示例

<html> 
   <head> 
      <script type = "text/javascript">  
         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" onclick = "WriteCookie();"/> 
      </form> 
   </body> 
</html>

成功执行上述代码后将显示以下输出。

Cookies

现在您的机器有一个名为 name 的 cookie。您可以使用多个以逗号分隔的 key = value 对来设置多个 cookie。

读取 Cookies

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

您可以使用字符串的 split() 函数将字符串分解为键和值,如以下示例所示。

示例

<html> 
   <head> 
      <script type = "text/javascript"> 
         function ReadCookie() {  
            var allcookies  =  document.cookie;  
            document.write ("All Cookies : " + allcookies ); 
         } 
         // 获取数组中的所有 cookie 对
         cookiearray = allcookies.split(';');  
         
         // 现在从该数组中取出键值对
         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> 

注意 − 此处,length 是 Array 类的一个方法,它返回数组的长度。

您的机器上可能已经设置了一些其他 cookie。上面的代码将显示您机器上设置的所有 cookie。

成功执行上述代码后将显示以下输出。

Reading Cookies

设置 Cookie 到期日期

您可以通过设置到期日期并在 cookie 中保存到期日期来延长 cookie 的使用寿命。这可以通过将"expires"属性设置为日期和时间来实现。以下示例说明如何将 cookie 的到期日期延长 1 个月。

示例

<html> 
   <head> 
      <script type = "text/javascript"> 
         function WriteCookie() {  
            var now = new Date();  
            now.setMonth( now.getMonth() + 1 );  
            cookievalue = escape(document.myform.customer.value) + ";"  
            document.cookie = "name = " + cookievalue;  
            document.cookie = "expires = " + now.toUTCString() + ";"  
            document.write ("Setting Cookies : " + "name = " + cookievalue );  
         } 
      </script> 
   </head> 

   <body> 
      <form name = "formname" action = ""> 
         Enter Cookie Name: <input type = "text" name = "customer"/> 
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/> 
      </form> 
   </body> 
</html> 

成功执行上述代码后将显示以下输出。

Cookies Expiry Date

删除 Cookie

有时,您会想要删除 Cookie,以便后续尝试读取 Cookie 时不会返回任何内容。为此,您只需将到期日期设置为过去的某个时间。以下示例说明了如何通过将 Cookie 的到期日期设置为当前日期后一个月来删除 Cookie。

示例

<html> 
   <head> 
      <script type = "text/javascript"> 
         function WriteCookie() {  
            var now = new Date();  
            now.setMonth( now.getMonth() - 1 );  
            cookievalue = escape(document.myform.customer.value) + ";" 
            document.cookie = "name=" + cookievalue;  
            document.cookie = "expires = " + now.toUTCString() + ";"  
            document.write("Setting Cookies : " + "name = " + cookievalue );  
         }  
      </script> 
   </head> 

   <body> 
      <form name = "formname" action = ""> 
         Enter Cookie Name: <input type = "text" name = "customer"/> 
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/> 
      </form> 
   </body> 
</html>

成功执行上述代码后将显示以下输出。

Deleting Cookie