JavaScript學習之cookies


使用JavaScript操作cookies

一、什么是cookies?

  cookies是一種對客戶端硬盤的數據進行存取的技術,這種技術能夠讓網站把少量的數據存儲到客戶端的硬盤,同時也能夠從客戶端的硬盤讀取存儲的數據。存儲的方式表現為一個很小的文本文件,這個文件可以存儲的東西很多,比如:用戶名、訪問時間、密碼等。

二、使用cookies

1、cookies的創建

document.cookies = name+"="+value;

  cookies的創建需要給出cookies的名稱和對應的cookies值,必備屬性是cookies的名稱name,除此之外,cookies還有四個另外的可選屬性,分別是:expires屬性、path屬性、domain屬性、secure屬性。

2、給cookies命名

  name屬性是用來唯一表示cookies的,cookies的name屬性可以自定義。與其他屬性不同,document對象的cookies屬性賦值時,並不會替代原來的值,而是會創建新的cookies。

eg:

1 document.cookies = "user=Tom";
2 document.cookies = "city=nanjing";
3 document.cookies = "age=20";

  上面的三條語句,創建了三個cookies。創建多個cookies時可以用一條語句,中間用分號隔開即可。

  因為cookies是通過HTTP來傳遞的,而HTTP不允許某個非字母和數字的字符被傳遞,因此cookies不能包含分號等特殊字符。為了解決這個問題,可以采用對cookies的名稱和值在賦值前進行編碼的方法。在JavaScript中,常用的編碼方法是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>

效果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM