ES6 - Cookie



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

它是如何工作的?

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

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

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

  • Domain - 您网站的域名。

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

  • Secure - 如果此字段包含“secure”一词,则 Cookie 只能通过安全服务器检索。如果此字段为空,则不存在此类限制。

  • Name = Value - 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 值可能不包含分号、逗号或空格。因此,您可能希望在将值存储在 Cookie 中之前使用 JavaScript 的escape()函数对其进行编码。如果这样做,您还必须在读取 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。您可以使用多个以逗号分隔的键=值对设置多个 Cookie。

读取 Cookie

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

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

示例

<html> 
   <head> 
      <script type = "text/javascript"> 
         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> 

注意 - 这里,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
广告