JavaScript和Cookie

什么是Cookie?

Web浏览器和服务器使用HTTP协议进行通信,HTTP是无状态协议。但对于商业网站,需要在不同页面之间维护会话信息。例如,一个用户注册在完成许多页面后结束。但是如何在所有网页上维护用户的会话信息。

在许多情况下,使用cookie是记住和跟踪首选项,购买,佣金和其他所需信息的最有效方法。为了更好的访问者体验或网站统计信息。

工作原理?

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

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

  • 过期 :  Cookie过期的日期。如果这是空白,则当访问者退出浏览器时,Cookie将过期。

  • : 您网站的域名。

  • 路径 : 设置cookie的目录或网页的路径。如果您想从任何目录或页面检索cookie,这可能是空白。

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

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

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

JavaScript can还使用 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()函数。

示例

请尝试以下操作。它在输入cookie中设置客户名称。

在线演示

<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 Cookie" onclick = "WriteCookie();"/>
      </form>   
   </body>
</html>

输出

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

读 Cookies

读取cookie就像写一个cookie一样简单,因为document.cookie对象的值是cookie。 因此,只要您想访问cookie,就可以使用此字符串。 document.cookie字符串将保留由分号分隔的名称=值对的列表,其中name是cookie的名称,value是其字符串值。


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

示例

请尝试以下示例来获取所有Cookie

在线演示

<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。

设置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 = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>

删除一个 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 = "myform" action = "">
         Enter name: <input type = "text" name = "customer"/>
         <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
      </form>      
   </body>
</html>