CS21AProject4
Download
Report
Transcript CS21AProject4
1
CS 21A
• Beginning JavaScript
Programming
Project 4 Cookies, Arrays, and Frames
Sonny Huang
2
Project 4 Cookies, Arrays, and Frames
Outline
l
Create a cookie
l
Use a cookie to store information from a Web page
l
Set the expiration date on a cookie
l
Read a cookie
l
Explain the use of the escape() and unescape() functions
l
Delete a cookie
l
Determine the contents of a cookie
3
Project 4 Cookies, Arrays, and Frames
Outline
l
Use the alert() method to debug JavaScript code
l
Create an array of objects
l
Populate an array of objects
l
Describe the attributes of an object
l
Use the new operator
l
Explain the use of the this keyword
l
Use a cookie to take action on a Web page
4
Project 4 Cookies, Arrays, and Frames
Outline
l
l
Set a flag in a cookie
Write information to a frame using JavaScript
5
Introduction
o
This project introduces creating and reading cookies using
various JavaScript methods.
o
We will learn about creating and using special arrays called
objects using the new and this keywords.
o We ,also, will learn how to use JavaScript to communicate
with frames using the TARGET keyword and top object.
o
The project illustrates how to use the alert() method to debug
their JavaScript code.
o
Finally, we will use the escape() and unescape() functions to
store information correctly in a cookie.
6
Introduction
7
Introduction
8
Introduction
cookie
A message given to a Web browser by a Web server. The
browser stores the message in a text file. The message is then
sent back to the server each time the browser requests a page
from the server.
The main purpose of cookies is to identify users and possibly
prepare customized Web pages for them.
When you enter a Web site using cookies, you may be asked
to fill out a form providing such information as your name
and interests.
9
Introduction
This information is packaged into a cookie and sent to your
Web browser which stores it for later use.
The next time you go to the same Web site, your browser will
send the cookie to the Web server.
The server can use this information to present you with
custom Web pages. So, for example, instead of seeing just a
generic welcome page you might see a welcome page with
your name on it.
The name cookie derives from UNIX objects called magic
cookies. These are tokens that are attached to a user or
program and change depending on the areas entered by the
user or program.
10
Introduction
This information is packaged into a cookie and sent to your
Web browser which stores it for later use.
The next time you go to the same Web site, your browser will
send the cookie to the Web server.
The server can use this information to present you with
custom Web pages. So, for example, instead of seeing just a
generic welcome page you might see a welcome page with
your name on it.
The name cookie derives from UNIX objects called magic
cookies. These are tokens that are attached to a user or
program and change depending on the areas entered by the
user or program.
11
Project Four – Student Council Web site
Needs:
On the first page (fig a) allows the viewer to change the
activities listed on the main student council web page shown
in the left frame in fig b.
By entering name and check boxes allow the user to select
the organizations that page displays the student name and the
organizations selected in the Student Council Preference Web
Page(fig a).
When the user clicks an organization name, the browser
loads the appropriate organization’s Web page in the right
frame of the Student Council Web page(fig c)
12
Project Four – Student Council Web site
data validation requirement:
name area can not be empty
13
Project Four – Student Council Web site
Starting Notepad
and opening the
council.htm file
14
Creating the cookie
A cookie is a small piece of information stored on the
client machine in the cookies.txt file in Navigator client.
We can manipulate cookies
o Explicitly, with a CGI program.
o Programmatically, with client-side JavaScript using the
cookie property of the document object.
o
Transparently, with the LiveWire the client object, when
using client-cookie maintenance.
15
Creating the cookie
We will concentrate on using JavaScript to manipulate
cookies.
Each cookie is a small item of information with an optional
expiration date and is added to the cookie file in the
following format:
name=value;expires=expDate;
name is the name of the datum being stored, and value is its
value.
expDate is the expiration date, in GMT date format:
Wdy, DD-Mon-YY HH:MM:SS
16
Creating the cookie
Greenwich Mean Time (GMT), as well as local time
methods. GMT, also known as UTC (universal) methods,
refers to the time as set by the World Time Standard. The
local time is the time known to the computer where
JavaScript is executed.
Although it's slightly different from this format, the date
string returned by the Date method toGMTString can be
used to set cookie expiration dates.
The expiration date is an optional parameter indicating how
long to maintain the cookie. If expDate is not specified, the
cookie expires when the user exits the current Navigator
session.
17
Creating the cookie
Navigator maintains and retrieves a cookie only if its
expiration date has not yet passed.
Limitations
Cookies have these limitations
o
Three hundred total cookies in the cookie file.
o
4 Kbytes per cookie, for the sum of both the cookie's name
and value.
o
Twenty cookies per server or domain (completely specified
hosts and domains are treated as separate entities and have a
twenty-cookie limitation for each, not combined).
18
Creating the cookie
Cookies can be associated with one or more directories. If
your files are all in one directory, then you need not worry
about this. If your files are in multiple directories, you may
need to use an additional path parameter for each cookie.
Using cookies with JavaScript
The document.cookie property is a string that contains all the
names and values of Navigator cookies. You can use this
property to work with cookies in JavaScript.
19
Creating the cookie
Here are some basic things you can do with cookies:
o
Set a cookie value, optionally specifying an expiration date.
o
Get a cookie value, given the cookie name.
It is convenient to define functions to perform these tasks.
Here, for example, is a function that sets cookie values and
expiration:
20
Creating the cookie
// Sets cookie values. Expiration date is optional
//
function setCookie(name, value, expire) {
document.cookie = name + "=" + escape(value)
+ ((expire == null) ? "" : ("; expires=" +
expire.toGMTString()))
}Notice the use of escape to encode special characters
(semicolons, commas, spaces) in the value string. This
function assumes that cookie names do not have any special
characters.
21
Creating the cookie
To create the cookie, perform the following two steps:
(1) write the function that create the cookie.
(2) add the JavaScript code that calls the function that create
the cookie.
Creating the addCookie() Function
To create the addCookie function, perform the following two
steps:
(1) set a date variable for the cookie experation date to a date
that is one year from now.
(2) Set the cookie value for the current document.
22
Creating the cookie
getTime ()
One of the Date object method. Returns the numeric value
corresponding to the time for the specified date.
23
Creating the cookie
A browser stores cookies in a file or files in a special
directory on the user’s computer.
A separate file may exist on the user’s computer for each
cookie storing Web page that the user has visited.
For security and privacy , by default the browser allows a
Web page to have access only to the Web page’s own
cookies on the user’s computer.
The browser stores as many values as required by the Web
page.
24
Creating the cookie
The browser stores these values as name and value pairs.
25
Creating the cookie
The escape() function converts the string by changing all
punctuation, spaces, accented characters, and other nonASCII characters to a special hexadecimal notation.
26
Creating the cookie
27
Creating the cookie
Calling the addCookie() Function
28
Creating the cookie
29
Creating the cookie
30
Creating the cookie
Calling the addCookie() Function
31
Reading the Cookie
Generic functions
Programmers refer to functions, such as addCookie() and
getCookie(), which can be used again and again without any
modification.
The steps to read the cookie:
1). Read the cookie that was created with the updateValues()
function
2). Test to make sure that the browser property saved the
cookie by displaying the value using the JavaScript alert()
function.
32
Reading the Cookie
Creating the getCookie() function
33
Reading the Cookie
The getCookie() function accepts the tag name of the cookie
that we want to read as a parameter.
The function searchs through all of the cookie’s name and
value pairs in the current web page to find if the name exists
in the cookie.
If the name exists, the function returns the value of the
cookie to the calling function.
34
Reading the Cookie
escape
o
Function. Returns the ASCII encoding of an argument in the
ISO Latin-1 character set.
o
Syntax
o escape("string")
o
Parameters
o
string is a nonalphanumeric string in the ISO Latin-1
character set, or a property of an existing object.
35
Reading the Cookie
o
Description
The value returned by the escape function is a string of the
form "%xx," where xx is the ASCII encoding of a character
in the argument.
If you pass the escape function an alphanumeric character,
the escape function returns the same character.
escape is a top-level function not associated with any object.
36
Reading the Cookie
o
Examples
The following example returns "Hello%2C%20World":
escape("Hello, World")
The following example returns "%26":
escape("&")
The following example returns "%21%23":
escape("!#")
37
Reading the Cookie
The getCookie() function accepts the tag name of the cookie
that we want to read as a parameter. The function searchs
through all of the cookie’s name and value pairs in the
current web page to find if the name exists in the cookie. If
the name exists, the function returns the value of the cookie
to the calling function.
38
Reading the Cookie
39
Reading the Cookie
Calling the getcookie() function
40
Reading the Cookie
Calling the getcookie() function
41
Reading the Cookie
Deleting a Cookie(call from the Clear All button)
42
Reading the Cookie
43
Reading the Cookie
Deleting a Cookie(call from the Clear All button)
44
Reading the Cookie
45
Creating the Array
Using array to store each organization’s web page
information. The array contains the information about a
user’s selected list of organization. The array’s information
will be used to update the lower-right frame in the following
figure.
46
Creating the Array
Initializing the Array
We will use the cookie’s information, which is
created in the Student Council Preferences Web page,
and populate the array in sidebar.htm file.
47
Creating the Array
this keyword
Use the this keyword to refer to the current object. In
general, this refers to the calling object in a method.
Use this as follows:
this[.propertyName]
48
Creating the Array
Example 1. Suppose a function called validate validates an
object's value property, given the object and the high and
low values:
function validate(obj, lowval, hival) {
if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}
49
Creating the Array
You could call validate in each form element's onChange
event handler, using this to pass it the form element, as in
the following example:
<B>Enter a number between 18 and 99:</B>
<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">
50
Creating the Array
Example 2. When combined with the form property, this can
refer to the current object's parent form.
In the following example, the form myForm contains a Text
object and a button.
When the user clicks the button, the value of the Text object
is set to the form's name.
The button's onClick event handler uses this.form to refer to
the parent form, myForm.
51
Creating the Array
<FORM NAME="myForm">
Form name:<INPUT TYPE="text" NAME="text1"
VALUE="Beluga">
<P>
<INPUT NAME="button1" TYPE="button"
VALUE="Show Form Name"
onClick="this.form.text1.value=this.form.name">
</FORM>
52
Creating the Array
The ClubArray() function accepts a parameter that
indicates how many elements will be in the array.
53
Creating the Array
The AddClub() function acreated an object entry for the
club that is passed to it.
54
Creating the Array
Populating the Array
55
Creating the Array
Populating the Array
56
Creating the Array
57
Displaying Data Based on a Cookie Value
Reading the Cookie
“= “
58
Displaying Data Based on a Cookie Value
59
Displaying Data Based on a Cookie Value
Displaying the Student Name
60
Displaying Data Based on a Cookie Value
61
Displaying Data Based on a Cookie Value
Displaying the Organization List
62
Displaying Data Based on a Cookie Value
63
Displaying Data Based on a Cookie Value
64
Displaying Data Based on a Cookie Value
65
Setting a Flag in a Cookie
When we want to go back to the student council preference
page by using back button on browser we will see we can
not go back to the previous page due to the existence of
StudentName cookie.
We have to let the browser know that that the user want to
change his/hers preferences, so the the JavaScript will not
automatically jump to the Student Council Web page.
66
Setting a Flag in a Cookie
top
Property. The top property is a synonym for the top-most
Navigator window, which is a "document window" or "Web
Browser window."
Syntax
1. top.propertyName
2. top.methodName
3. top.frameName
4. top.frames[index]
67
Setting a Flag in a Cookie
Parameters
propertyName is defaultStatus, status, or length.
methodName is any method associated with the window
object.
frameName and frames[index] are ways to refer to frames.
Description
The top property refers to the top-most window that contains
frames or nested framesets. Use the top property to refer to
this ancestor window.
68
Setting a Flag in a Cookie
The top property is read-only. The value of the top property
is
<object objectReference>where objectReference is an
internal reference.
Examples
The statement top.close() closes the top-most ancestor
window.
69
Setting a Flag in a Cookie
The statement top.length specifies the number of frames
contained within the top-most ancestor window. When the
top-most ancestor is defined as follows, top.length returns
three:
<FRAMESET COLS="30%,40%,30%">
<FRAME SRC=child1.htm NAME="childFrame1">
<FRAME SRC=child2.htm NAME="childFrame2">
<FRAME SRC=child3.htm NAME="childFrame3">
</FRAMESET>
70
Setting a Flag in a Cookie
The following example sets the background color of a
frame called myFrame to red. myFrame is a child of the
top-most ancestor window.
top.myFrame.document.bgColor="red"
71
Setting a Flag in a Cookie
Setting the Value of the Flag
72
Setting a Flag in a Cookie
73
Setting a Flag in a Cookie
74
Setting a Flag in a Cookie
Reading and Using the Flag
75
Setting a Flag in a Cookie
76
Initializing the Web Page
The InitialValue() function reads the existing
cookies and sets the values on the Student
Council Preference page.
77
Initializing the Web Page
78
Initializing the Web Page
79
Working with Frames
80
Working with Frames
<FRAMESET COLS="160, *" FRAMEBORDER=YES>
<FRAME NAME="SIDEBAR" SRC="side.htm" MARGINWIDTH=0
MARGINHEIGHT=10>
<FRAMESET ROWS="135,448*" FRAMEBORDER=NO BORDER=0
FRAMESPACING=0>
<FRAME NAME="HEADER" SRC="header.htm" MARGINHEIGHT=0
MARGINWIDTH=0>
<FRAME NAME=
"LOWERRIGHT“
SRC="welcome.htm"
MARGINHEIGHT=0
MARGINWIDTH=0>
</FRAMESET> </FRAMESET>
81
Working with Frames
Setting the contents of the display frame