Học JavaScript qua ví dụ part 80 pps

10 209 0
Học JavaScript qua ví dụ part 80 pps

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 16.2 Creating a Cookie with JavaScript 701 Path. The path is used to specify where the cookie is valid for a particular server. Set- ting a path for the cookie allows other pages from the same domain to share a cookie. Secure. If a cookie is secure, it must be sent over a secure communication channel (HTTPS server). 16.2 Creating a Cookie with JavaScript In the following examples, we will create a cookie, view the cookie, and then destroy it. It is important to note when you are setting cookies that they are stored in the browser’s memory and not written to the hard drive until you exit the browser. 16.2.1 The Cookie Object The cookie is stored by JavaScript as a document object for both reading and writing cookie data. Cookies are made by assigning attributes to the cookie property. When you start your browser, if there are cookies, they pertain to the current document. The doc- ument.cookie property contains a string of name=value pairs representing the names of all the cookies and their corresponding values, such as a session ID number or a user ID. All the other attributes set for the cookie, such as expiration date, path, and secure, are not visible. In a JavaScript program, if you execute the statement shown in Figure 16.5, you will see all the cookies set for this page. FORMAT ; path=pathname EXAMPLE ; path=/home FORMAT ; secure Figure 16.5 Using alert(document.cookie); From the Library of WoweBook.Com ptg 702 Chapter 16 • Cookies When you reload the page, the document.cookie property will contain all the cookie text saved for that page. 16.2.2 Assigning Cookie Attributes To create a cookie, assign the name=value pairs to the document.cookie property. Be care- ful with quotes, making sure the variables you use are not quoted, but the text that the cookie needs, such as the word “name”, and “=” are quoted. Also, this will be a big string where the different parts are concatenated together with the + operator. The following format sets a cookie using all possible attributes. Those attributes enclosed in square brackets are optional: The escape() and unescape() Built-In Functions. It is important to know that when assigning string name=value attributes to a cookie, you cannot use whitespace, semicolons, or commas. The escape() function will encode the string object by convert- ing all nonalphanumeric characters to their hexadecimal equivalent, preceded by a per- cent sign; for example, %20 represents a space and %26 represents an ampersand. To send information back and forth between browser and server, the browser encodes the data in what is called URI encoding. You can see this encoding in the location bar of your browser; when you go to Google and search for something, you will see the search string in the location bar of the browser all encoded. Because the browser handles cookies, the cookie strings can be encoded with JavaScript’s built-in escape() function to ensure that the cookie values are valid. The unescape() function converts the URI-encoded string back into its original for- mat and returns it. The encodeURI() and decodeURI() built-in functions are a more recent version of escape() and unescape() and do not encode as many characters. FORMAT name=value;[expires=date];[path=path];[domain=somewhere.com];[secure] EXAMPLE document.cookie="id=" + form1.cookie.value ";expires=" + expiration_date+";path=/"; EXAMPLE 16.1 <html> <head> <title>The escape() Method</title> <script type="text/javascript"> From the Library of WoweBook.Com ptg 16.2 Creating a Cookie with JavaScript 703 1 function seeEncoding(form){ var myString = form.input.value; 2 alert(escape(myString)); } 3 function seeDecoding(form){ var myString = form.input.value; 4 alert(unescape(myString)); } </script> </head> <body background="cookebg.jpg" > <div align="center"><h2>URL Encoding </h2> <form name="form1"> Type in a string of text: <p> <input type="text" name="input" size=40 /> </p><p> <input type="button" value="See encoding" 5 onClick="seeEncoding(this.form);"/> </p><p> <input type="button" value="See decoding" 6 onClick="seeDecoding(this.form);"/> </p> </form> </div> </body> </html> EXPLANATION 1 A function called seeEncoding() is defined. It takes a reference to a form as its only parameter. 2 The built-in escape() function is used to URI encode the string that was entered as input by the user. 3 A function called seeDecoding() is defined. It takes a reference to a form as its only parameter. 4 The built-in unescape() function is used to convert the URI encoded string back into its original ASCII format. 5 When the user clicks this button, the onClick event is triggered and the encoded string will appear in an alert dialog box. 6 When the user clicks this button, the onClick event triggers a function that will decode the encoded string. See Figures 16.6 and 16.7. EXAMPLE 16.1 (CONTINUED) From the Library of WoweBook.Com ptg 704 Chapter 16 • Cookies 16.2.3 Let’s Make Cookies! Now that we have all the ingredients, let’s put them together and make a cookie, then pull it out of the oven (your program) and enjoy a delicious cookie for your browser. The following example creates two cookies called “visitor” and “color”. The value assigned to it will be the visitor’s name and his or her favorite color. You will see this name=value pair in the document.cookie property. Once this page has been viewed, the cookie values are saved on the browser in a cookie file. The next time a user views a page on this site, the cookie values are available. In Example 16.2 we will retrieve the cookies on a different page and use the user preferences gleaned from a cookie to change the background color of the page. Figure 16.6 Using the escape() and unescape() functions. Figure 16.7 The user pressed the “See encoding” button (top); the user pressed the “See decoding” button (bottom). From the Library of WoweBook.Com ptg 16.2 Creating a Cookie with JavaScript 705 EXAMPLE 16.2 <html> <head><title>Making Cookies</title> <script type="text/javascript"> 1 function makeCookie(form){ 2 var when = new Date(); when.setTime(when.getTime() + 24 * 60 * 60 * 1000); // 24 hours from now 3 when.setFullYear(when.getFullYear() + 1); // One year from now yname=form.yourname.value; favcolor=form.yourcolor.value; 4 document.cookie=escape("visitor")+"="+escape(yname)+ ";expires="+when.toGMTString(); document.cookie=escape("color")+"="+escape(favcolor)+ ";expires="+when.toGMTString(); alert(document.cookie); } 5 function welcome(myForm){ you=myForm.yourname.value; 6 var position=document.cookie.indexOf("name="); if ( position != -1){ var begin = position + 5; var end=document.cookie.indexOf(";", begin); if(end == -1){ end=document.cookie.length;} 7 you= unescape(document.cookie.substring(begin, end)); 8 alert("Welcome " + you); } else{ alert("No cookies today");} } </script> </head> <body onLoad="document.form1.reset()" > <div align="center"> <h2> Got milk?</h2> <form name="form1"> What is your name? <br /> 9 <input type="text" name="yourname" /> <br /> What is your favorite color? <br /> <input type="text" name="yourcolor" /> <br /> <p> 10 <input type="button" value="Make cookie" onClick="makeCookie(this.form);" /> </p> Continues From the Library of WoweBook.Com ptg 706 Chapter 16 • Cookies <p> 11 <input type="button" value="Get Cookie" onClick="welcome(this.form);"/> </p> </form> </div> </body> </html> EXPLANATION 1 A function called makeCookie() is defined. It takes a reference to a form as its only parameter. This is the function that creates the cookie. 2 A new Date object is created and assigned to the variable called when. 3 The Date object creates a date a year from now. This will be the expiration date for the cookie. 4 Two cookies are created. The first cookie’s name is “visitor” and its value is the us- er’s name, stored in yname. The second cookie’s name is “color” and its value stored in favcolor. Both values came from the form input. The attributes are es- caped just in case the user added unwanted characters, such as spaces, commas, or semicolons. The expiration date is set to a year from now and is converted to GMT time, the required format for the “expires” attribute. Notice the quotes. If the text is literal for the attribute it must be quoted; if it is a variable value, then it is not quoted or JavaScript can’t interpret it—very tricky getting these right. 5 A function called welcome() is created. It takes a reference to a form as its only parameter. Its purpose is to greet the user based on the cookie value. 6 The following statements are used to parse out the value attribute of the cookie. The beginning index position is set to where the “name=” string starts in the cook- ie string. It will be at position 5 in this example. Starting at index position 0, po- sition 5 takes us to the character directly after the = sign. The end position is ei- ther at the first semicolon or at the end of the string, whichever applies. 7 After getting the substring, the value part of the cookie, the unescape() function, will convert the URI-encoded string back into its original ASCII format. 8 The user is welcomed, all based on the value extracted from the cookie. The cook- ie lets this Web site know who you are so that you can get a personal greeting when you return to the site. 9 The user will enter his or her name in a textbox field. See Figure 16.8. 10 When the user clicks this button, the onClick event is triggered, and the cookie will be made. See Figure 16.9. 11 When the user clicks this button, the onClick event is triggered, and the user will be welcomed by the name he or she entered in the textbox. See Figure 16.10. EXAMPLE 16.2 (CONTINUED) From the Library of WoweBook.Com ptg 16.2 Creating a Cookie with JavaScript 707 Figure 16.8 Creating a cookie with user preferences. Figure 16.9 Contents of a cookie. From the Library of WoweBook.Com ptg 708 Chapter 16 • Cookies 16.2.4 Retrieving Cookies from a Server When retrieving cookies, you can only get those that were written for the server you are on and written by you. You cannot read and write cookies that belong to someone else or reside on a different server. In the last example, we got one cookie; in Example 16.3 all the cookies for this page are displayed. Figure 16.10 Retrieve the cookie and welcome the user. EXAMPLE 16.3 <html> <head><title>See my Cookies</title> <script type="text/javascript"> 1 function seeCookie(){ if(document.cookie == ""){ document.write("No cookies"); } else{ var cookiestr=""; 2 var myCookie = document.cookie.split("; "); 3 for(var i=0;i<myCookie.length; i++){ /* document.write("<b>Cookie: " + myCookie[i].split("=")[1] +"<br />"); */ 4 cookiestr+=myCookie[i] + " "; 5 var cookieData=myCookie[i].split("="); 6 if (cookieData[0] == "color"){ 7 document.bgColor=cookieData[1]; //Visitor preference to change color } From the Library of WoweBook.Com ptg 16.2 Creating a Cookie with JavaScript 709 } } 8 alert(cookiestr); } </script> </head> 9 <body onLoad="document.form1.reset()" > <div align="center"><h2> Got milk?</h2> <form name="form1"> Click to see document.cookie property <p> 10 <input type="button" value="See Cookie" onClick="seeCookie();"/> </p> </form> </div> </body> </html> EXPLANATION 1 A function called seeCookie() is defined. It will list out all the cookies that have been set. First, we check to see if there are any cookies at all. If not, the alert box will say so. 2 The split function splits up the cookie string by semicolons and returns an array called myCookie. 3 The for loop iterates through each element of the myCookie array until the end of the array, myCookie.length, is reached. 4 Each time we get a cookie it is appended to this string, called cookiestr. 5 The name/value pairs of the cookie string are split by “=” signs. An array is re- turned. 6 If the name assigned to the cookie is “color”, that name is stored in cookieData[0] and the color choice of the user is stored in cookieData[1]. 7 Based on the user’s preference of color, the background color of the page is changed. 8 The alert box displays all the cookies that were retrieved. 9 When the document is loaded and every time the user refreshes the page, the on- Load event is triggered and the values in the form are cleared with the reset() method. 10 When the user clicks the button, the onClick event is triggered, and the seeCook- ie() function will be called to display all the cookies for this page. The process is shown in Figures 16.11 and 16.12. EXAMPLE 16.3 (CONTINUED) From the Library of WoweBook.Com ptg 710 Chapter 16 • Cookies 16.2.5 Deleting a Cookie If you want to delete a cookie for the current page, set the expiration date of the cookie to a date earlier than the current date. This will cause the cookie to be deleted when the session ends. Figure 16.11 When the user clicks the “See Cookie” button, all cookies are retrieved. Figure 16.12 After the user clicks the button, the color of the page changes based on the cookie that was sent. EXAMPLE 16.4 <html> <head><title>Delete Cookie</title><head> <script type = "text/javascript"> var i = 0; 1 function delCookie (cookieName){ 2 document.cookie = cookieName + "=" +"; expires=Thu, 01-Jan-1970 00:00:01 GMT"; alert("Cookie was deleted!"); seeCookie(); } From the Library of WoweBook.Com . ptg 16.2 Creating a Cookie with JavaScript 701 Path. The path is used to specify where the cookie is valid for a particular server. Set- ting a path for the cookie allows. where the different parts are concatenated together with the + operator. The following format sets a cookie using all possible attributes. Those attributes enclosed in square brackets are optional: The. escape() Method</title> <script type="text /javascript& quot;> From the Library of WoweBook.Com ptg 16.2 Creating a Cookie with JavaScript 703 1 function seeEncoding(form){ var myString

Ngày đăng: 04/07/2014, 02:20

Tài liệu cùng người dùng

Tài liệu liên quan