1. Trang chủ
  2. » Công Nghệ Thông Tin

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

10 210 0
Tài liệu đã được kiểm tra trùng lặp

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 876,44 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

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.. 5 When the user clicks thi

Trang 1

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

F O RM A T

; path=pathname

E X A M P L E

; path=/home

F O RM A T

; secure

Trang 2

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

F O RM A T

name=value;[expires=date];[path=path];[domain=somewhere.com];[secure]

E X A M P L E

document.cookie="id=" + form1.cookie.value ";expires=" +

expiration_date+";path=/";

E X A M P L E 1 6 1

<html>

<head>

<title>The escape() Method</title>

<script type="text/javascript">

Trang 3

1 function seeEncoding(form){

var myString = form.input.value;

}

3 function seeDecoding(form){

var myString = form.input.value;

}

</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>

E X P L A N A T I O N

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

E X A M P L E 1 6 1 (C O N T I N U E D)

Trang 4

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).

Trang 5

E X A M P L E 1 6 2

<html>

<head><title>Making Cookies</title>

<script type="text/javascript">

1 function makeCookie(form){

when.setTime(when.getTime() + 24 * 60 * 60 * 1000);

// 24 hours from now

// 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);" />

Trang 6

<p>

11 <input type="button"

value="Get Cookie" onClick="welcome(this.form);" />

</p>

</form>

</div>

</body>

</html>

E X P L A N A T I O N

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 popo-sition 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

E X A M P L E 1 6 2 (C O N T I N U E D)

Trang 7

Figure 16.8 Creating a cookie with user preferences.

Trang 8

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.

E X A M P L E 1 6 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"){

//Visitor preference to change color }

Trang 9

} }

}

</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>

E X P L A N A T I O N

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

E X A M P L E 1 6 3 (C O N T I N U E D)

Trang 10

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.

E X A M P L E 1 6 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();

}

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

TỪ KHÓA LIÊN QUAN