Another mechanism in JavaScript: cookies, can meet the requirements of true global variables. A cookie is a mechanism provided by the browser that provides the cookie attribute of the document object to JavaScript. It can be controlled by JavaScript and is not a property of JavaScript itself.
Cookie Overview
In the previous section, an immutable framework was used to store the shopping column data, while the product display page was constantly changing. Although this can achieve the function of simulating global variables, it is not rigorous. For example, if you right-click in the navigation frame page and click the [Refresh] command in the shortcut menu, all JavaScript variables will be lost. Therefore, to implement strict cross-page global variables, this method is not feasible. Another mechanism in JavaScript: cookies can meet the requirements of true global variables.
Cookie is a mechanism provided by the browser, which provides the cookie attribute of the document object to JavaScript. It can be controlled by JavaScript and is not a property of JavaScript itself. A cookie is a file stored on the user's hard drive. This file usually corresponds to a domain name. When the browser accesses the domain name again, the cookie is made available. Therefore, cookies can span multiple web pages under one domain name, but cannot be used across multiple domain names.
Different browsers implement cookies differently, but their properties are the same. For example, in Windows 2000 and Windows xp, cookie files are stored in the documents and settingsuserNamecookie folder. The usual naming format is: userName@domain.txt.
The cookie mechanism stores information on the user's hard drive, so it can be used as a global variable, which is one of its biggest advantages. It can be used in the following situations.
(1) Save user login status. For example, the user ID is stored in a cookie so that the user does not need to log in again when he visits the page next time. Many forums and communities now provide this function. Cookies can also set an expiration time. When the time limit expires, the cookie will automatically disappear. Therefore, the system can often prompt users to stay logged in: common options are one month, three months, one year, etc.
(2) Track user behavior. For example, a weather forecast website can display local weather conditions based on the area selected by the user. If you need to select the location every time, it will be cumbersome. When cookies are used, it will become very user-friendly. The system can remember the area visited last time. When the page is opened next time, it will automatically display the last user. Weather conditions in your area. Because everything is done in the background, such a page is as customized as a user and is very convenient to use.
(3) Customized page. If the website provides the function of changing the skin or changing the layout, cookies can be used to record the user's options, such as background color, resolution, etc. When the user visits next time, the interface style of the last visit can still be saved.
(4) Create shopping cart. Just like in the previous example, cookies are used to record the items that the user needs to purchase, and they can be submitted uniformly during checkout. For example, Taobao uses cookies to record the products that users have browsed so that they can be compared at any time.
Of course, the above applications are only some of the applications that cookies can complete, and there are more functions that require global variables. The disadvantages of cookies mainly focus on security and privacy protection. Mainly include the following categories:
(1) Cookies may be disabled. When a user attaches great importance to personal privacy protection, he is likely to disable the cookie function of the browser;
(2) Cookies are browser-related. This means that even if you visit the same page, the cookies saved by different browsers cannot access each other;
(3) Cookies may be deleted. Because each cookie is a file on the hard drive, it is likely to be deleted by the user;
(4) Cookie security is not high enough. All cookies are recorded in files in the form of plain text, so if you want to save username, password and other information, it is best to encrypt it in advance.
Set cookies
Each cookie is a name/value pair. You can assign the following string to document.cookie:
document.cookie="userId=828";
If you want to store multiple name/value pairs at one time, you can use semicolons and spaces (;) to separate them, for example:
document.cookie="userId=828; userName=hulk";
Semicolons (;), commas (,), equal signs (=), and spaces cannot be used in cookie names or values. It's easy to do this in the name of the cookie, but the value to be saved is undefined. How to store these values? The method is to use the escape() function to encode, which can use hexadecimal representation of some special symbols. For example, spaces will be encoded as "20%", which can be stored in the cookie value, and using this solution can also avoid The emergence of Chinese garbled characters. For example:
document.cookie="str="+escape("I love ajax");
Equivalent to:
document.cookie="str=I%20love%20ajax";
当使用escape()编码后,在取出值以后需要使用unescape()进行解码才能得到原来的cookie值,这在前面已经介绍过。
尽管document.cookie看上去就像一个属性,可以赋不同的值。但它和一般的属性不一样,改变它的赋值并不意味着丢失原来的值,例如连续执行下面两条语句:
document.cookie="userId=828"; document.cookie="userName=hulk";
这时浏览器将维护两个cookie,分别是userId和userName,因此给document.cookie赋值更像执行类似这样的语句:
document.addCookie("userId=828"); document.addCookie("userName=hulk");
事实上,浏览器就是按照这样的方式来设置cookie的,如果要改变一个cookie的值,只需重新赋值,例如:
document.cookie="userId=929";
这样就将名为userId的cookie值设置为了929。
获取cookie的值
下面介绍如何获取cookie的值。cookie的值可以由document.cookie直接获得:
var strCookie=document.cookie;
这将获得以分号隔开的多个名/值对所组成的字符串,这些名/值对包括了该域名下的所有cookie。例如:
从输出可知,只能够一次获取所有的cookie值,而不能指定cookie名称来获得指定的值,这正是处理cookie值最麻 烦的一部分。用户必须自己分析这个字符串,来获取指定的cookie值,例如,要获取userId的值,可以这样实现:
这样就得到了单个cookie的值。
用类似的方法,可以获取一个或多个cookie的值,其主要的技巧仍然是字符串和数组的相关操作。
给cookie设置终止日期
到现在为止,所有的cookie都是单会话cookie,即浏览器关闭后这些cookie将会丢失,事实上这些cookie仅仅是存储在内存中,而没有建立相应的硬盘文件。
在实际开发中,cookie常常需要长期保存,例如保存用户登录的状态。这可以用下面的选项来实现:
document.cookie="userId=828; expiress=GMT_String";
其中GMT_String是以GMT格式表示的时间字符串,这条语句就是将userId这个cookie设置为GMT_String表示的过期时间,超过这个时间,cookie将消失,不可访问。例如:如果要将cookie设置为10天后过期,可以这样实现:
<script language="JavaScript" type="text/javascript"> <!-- //获取当前时间 var date=new Date(); var expiresDays=10; //将date设置为10天以后的时间 date.setTime(date.getTime()+expiresDays*24*3600*1000); //将userId和userName两个cookie设置为10天后过期 document.cookie="userId=828; userName=hulk; expires="+date.toGMTString(); //--> </script>
删除cookie
为了删除一个cookie,可以将其过期时间设定为一个过去的时间,例如:
<script language="JavaScript" type="text/javascript"> <!-- //获取当前时间 var date=new Date(); //将date设置为过去的时间 date.setTime(date.getTime()-10000); //将userId这个cookie删除 document.cookie="userId=828; expires="+date.toGMTString(); //--> </script>
指定可访问cookie的路径
默 认情况下,如果在某个页面创建了一个cookie,那么该页面所在目录中的其他页面也可以访问该cookie。如果这个目录下还有子目录,则在子目录中也 可以访问。例如在www.xxxx.com/html/a.html中所创建的cookie,可以被www.xxxx.com/html/b.html或 www.xxx.com/ html/ some/c.html所访问,但不能被www.xxxx.com/d.html访问。
为了控制cookie可以访问的目录,需要使用path参数设置cookie,语法如下:
document.cookie="name=value; path=cookieDir";
其中cookieDir表示可访问cookie的目录。例如:
document.cookie="userId=320; path=/shop";
就表示当前cookie仅能在shop目录下使用。
如果要使cookie在整个网站下可用,可以将cookie_dir指定为根目录,例如:
document.cookie="userId=320; path=/";
指定可访问cookie的主机名
和 路径类似,主机名是指同一个域下的不同主机,例如:www.google.com和gmail.google.com就是两个不同的主机名。默认情况下, 一个主机中创建的cookie在另一个主机下是不能被访问的,但可以通过domain参数来实现对其的控制,其语法格式为:
document.cookie="name=value; domain=cookieDomain";
以google为例,要实现跨主机访问,可以写为:
document.cookie="name=value;domain=.google.com";
这样,所有google.com下的主机都可以访问该cookie。
综合示例:构造通用的cookie处理函数
cookie的处理过程比较复杂,并具有一定的相似性。因此可以定义几个函数来完成cookie的通用操作,从而实现代码的复用。下面列出了常用的cookie操作及其函数实现。
1.添加一个cookie:addCookie(name,value,expiresHours)
该函数接收3个参数:cookie名称,cookie值,以及在多少小时后过期。这里约定expiresHours为0时不设定过期时间,即当浏览器关闭时cookie自动消失。该函数实现如下:
<script language="JavaScript" type="text/javascript"> <!-- function addCookie(name,value,expiresHours){ var cookieString=name+"="+escape(value); //判断是否设置过期时间 if(expiresHours>0){ var date=new Date(); date.setTime(date.getTime+expiresHours*3600*1000); cookieString=cookieString+"; expires="+date.toGMTString(); } document.cookie=cookieString; } //--> </script>
2.获取指定名称的cookie值:getCookie(name)
该函数返回名称为name的cookie值,如果不存在则返回空,其实现如下:
<script language="JavaScript" type="text/javascript"> <!-- function getCookie(name){ var strCookie=document.cookie; var arrCookie=strCookie.split("; "); for(var i=0;i<arrCookie.length;i++){ var arr=arrCookie[i].split("="); if(arr[0]==name)return arr[1]; } return ""; } //--> </script>
3.删除指定名称的cookie:deleteCookie(name)
该函数可以删除指定名称的cookie,其实现如下:
<script language="JavaScript" type="text/javascript"> <!-- function deleteCookie(name){ var date=new Date(); date.setTime(date.getTime()-10000); document.cookie=name+"=v; expires="+date.toGMTString(); } //--> </script>
以上所述就是本文的全部内容了,希望大家能够喜欢。