JavaScript和Cookies

JavaScript和Cookies

什么是Cookies

网络浏览器和服务器使用HTTP协议进行通信,而HTTP是一种无状态的协议。但是对于商业网站来说,在不同的页面之间需要保持会话信息。例如,一个用户在完成多个页面后结束注册。但是如何在所有网页中保持用户的会话信息呢?

在许多情况下,使用cookies是记住和跟踪偏好、购买、佣金和其他与访客体验或站点统计信息相关的信息的最有效方法。

它是如何工作的

您的服务器以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。

存储Cookies

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

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

在这里, expires 属性是可选的。如果您提供了一个有效的日期或时间,那么cookie将在给定的日期或时间过期,此后,cookie的值将无法访问。

注意 − Cookie的值中不能包含分号、逗号或空白字符。出于这个原因,您可能希望在将值存储在cookie中之前使用JavaScript的 escape() 函数对其进行编码。如果这样做,您在读取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。你可以使用多个键=值对通过逗号分隔来设置多个cookie。

读取cookie

读取cookie与写入cookie一样简单,因为document.cookie对象的值就是cookie的值。所以你可以在任何时候使用这个字符串来访问cookie。document.cookie字符串将保持一个以分号分隔的name=value对的列表,其中 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>

注意 - 这里的 lengthArray 类的一个方法,它返回一个数组的长度。我们将在另一章节讨论数组。在那之前,请尝试理解它。

注意 - 可能已经在您的计算机上设置了一些其他的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>

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程