使用JavaScript操作cookies
一、什么是cookies?
cookies是一种对客户端硬盘的数据进行存取的技术,这种技术能够让网站把少量的数据存储到客户端的硬盘,同时也能够从客户端的硬盘读取存储的数据。存储的方式表现为一个很小的文本文件,这个文件可以存储的东西很多,比如:用户名、访问时间、密码等。
二、使用cookies
1、cookies的创建
document.cookies = name+"="+value;
cookies的创建需要给出cookies的名称和对应的cookies值,必备属性是cookies的名称name,除此之外,cookies还有四个另外的可选属性,分别是:expires属性、path属性、domain属性、secure属性。
2、给cookies命名
与其他属性不同,document对象的cookies属性赋值时,并不会替代原来的值,而是会创建新的cookies。
eg:
1 document.cookies = "user=Tom";
2 document.cookies = "city=nanjing";
3 document.cookies = "age=20";
上面的三条语句,创建了三个cookies。创建多个cookies时可以用一条语句,中间用分号隔开即可。
escape(),为了在读取的时候解码,相对应的一个解码方法是unescape().例如:
document.cookies = escape("user=Tom;city=nanjing;age=20");
3、定义cookies过期时间(expires属性)
(1)cookies是有生命周期的,为了能够让一个cookies能够在关闭浏览器后还能持续生效,就需要使用expires属性。expires需要使用格林尼治标准时间的文本字符串,格式如下:
Weekday Mon DD HH:MM:SS Time Zone YYYY
eg:
Mon Oct 22 13:22:34 PST 2012
(2)为了更好的控制时间,通常使用JavaScript的Date对象来进行时间的设置(这里就不列举Date对象的常用方法了,之前的学习中有详细的资料)
eg:
1 <script language="JavaScript">
2 var edate = new Date();
3 document.cookies = escape("user=Tom;expire="+edate.setFullYear(edate.getFullYear()+1));
4 </script>
以上代码,设置了过期时间为当前时间加一年。要想让一个cookies删除,通常也是使用expires属性设置为过去的某一个时间即可。例如:
1 <script language="JavaScript">
2 var edate = new Date();
3 document.cookies = escape("user=Tom;expire="+edate.setFullYear(edate.getFullYear()-1));
4 </script>
4、定义cookies的目录范围(path属性)
和变量的作用域一样,cookies一样有着自己的作用范围。path属性能使cookies能够被服务器上指定目录下的所有网站访问。
eg:cookies能够被服务器里www目录及其子目录下的任何网页访问到:
document.cookies = "user=Tom;path=/www";
如果cookies 能够被服务器上所有网页访问:
document.cookies = "user=Tom;path=/";
5、实现跨服务器共享(domain属性)
domain属性能够实现跨服务器的共享。比如对于某个网站的主站www.ds5u.com是一台服务器,但是其论坛站bbs.ds5u.com又是另一个服务器,博客站blog.ds5u.com又是另一台服务器。虽然这些网站都有各自的二级域名,但是用户是同一的,需要实现cookies的共享。例如:
document.cookies = "user=Tom;domain=.ds5u.com";
上述代码即可实现cookies在ds5u.com这个域所在的所有服务器共享。
6、使信息传输更加安全(secure属性)
secure属性规定cookies只能在安全的Internet上连接。通常情况下,此属性是忽略的,属性的可选值是true和false。
eg:
document.cookies = "user=Tom;secure=true";
三、让cookies存储信息
cookies 本身的使用是有限制的,在用户的计算机上,每个服务器或域只能保存最多20个cookies,而每个浏览器的cookies总数不能超过300,cookies的最大尺寸的4k,因此不能像使用变量一样,随意的创建cookies。考虑到cookies的限制,最有效的方法是将所有需要保存到cookies中的值链接为一个字串(使用分隔符分隔),然后把这个字串赋值给一个cookies。这样,只需要创建一个cookies,就能保存若干的信息了。读取时,按照分隔符的组合规则进行信息的提取和还原。
语法:
名称1=值1&名称2=值2&...&名称n=值n
eg:如果要保存姓名、年龄、性别、城市、邮编这五个消息,先将消息组合成一个字串:
user=Tom&age=25&sex=male&city=nanjing&zip=210000
然后创建一个cookies,因为字串中包含非字母和数字字符,因此在赋值前先进行编码:
document.cookie = "allinfo="+escape("user=Tom&age=25&sex=male&city=nanjing&zip=210000");
四、从cookies读取信息
创建cookies后,读取cookies信息直接访问属性即可:
document.cookie
document.cookie通常需要用unescape()方法进行解码,eg:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>JS</title>
6 <script language="JavaScript">
7 document.cookie = escape("user=Tom;city=nanjing;zip=21000");
8 alert("cookies的值:"+unescape(document.cookie));
9 </script>
10 </head>
11
12 <body>
13
14 </body>
15 </html>
效果:
在这里得到的值是一个用分号分隔的字符串。可以通过String对象来获得每个cookies对应的值。eg:
split():将字符串按照指定的分隔符分成数组。
substring(starting index,ending index):提取从starting index开始到ending index结束的文本。
indexOf(text,index):返回text参数内的第一个字符在字符串的位置。
eg:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>读取cookies</title>
6 </head>
7 <script language="JavaScript">
8 <!--
9 document.cookie = escape("username=tom;city=nanjing;zip=210000");
10 var allCookies = unescape(document.cookie);
11 var aryCookies = allCookies.split(";");
12 var nowvalue;
13 for( var i=0; i < aryCookies.length; i++ ){
14 nowvalue = aryCookies[i];
15 if( nowvalue.substring( 0, nowvalue.indexOf("=") ) == "zip" ){
16 document.write("cookies中保存的邮编是:"+nowvalue.substring( nowvalue.indexOf("=")+1, nowvalue.length));
17 alert("cookies中保存的邮编是:"+nowvalue.substring( nowvalue.indexOf("=")+1, nowvalue.length));
18 break;
19 }
20 }
21 //-->
22 </script>
23
24
25 <body>
26 </body>
27 </html>
效果:
(只能在IE中显示)
五、实践
eg:
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>JS</title>
6 <script language="JavaScript">
7 function getCookie(c_name) {
8 if (document.cookie.length>0) {
9 c_start=document.cookie.indexOf(c_name + "=")
10 if (c_start!=-1) {
11 c_start=c_start + c_name.length+1
12 c_end=document.cookie.indexOf(";",c_start)
13 if (c_end==-1) c_end=document.cookie.length
14 return unescape(document.cookie.substring(c_start,c_end))
15 }
16 }
17 return ""
18 }
19
20 function setCookie(c_name,value,expiredays) {
21 var exdate=new Date()
22 exdate.setDate(exdate.getDate()+expiredays)
23 document.cookie=c_name+ "=" +escape(value)+
24 ((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
25 }
26
27 function checkCookie() {
28 username=getCookie('username')
29 if (username!=null && username!="") {
30 alert('Welcome again '+username+'!')}
31 else {
32 username=prompt('Please enter your name:',"")
33 if (username!=null && username!="") {
34 setCookie('username',username,365)
35 }
36 }
37 }
38 </script>
39 </head>
40
41 <body onLoad="checkCookie()">
42
43 </body>
44 </html>
效果: