Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

the book of javascript 2nd edition phần 6 pot
Nội dung xem thử
Mô tả chi tiết
222 Chapter 12
<!-- hide me from older browsers
_ document.write("Name: " + cookie_information["name"] + "<br>");
document.write("Age: " + cookie_information["age"] + "<br>");
document.write("Phone: " + cookie_information["phone"] + "<br>");
// show me -->
</script>
</body>
</html>
Figure 12-6: Loading a complex cookie into an associative array
When this page loads, \ sets a cookie, ] creates a new array, and ^
sends the new, empty array to the readTheCookie() function. The function first
gets the cookie and splits off the cookie’s name (my_cookie). After X, the_values
will equal "name:thau/age:just a tyke/phone:411" because that’s how we set the
cookie in the setCookie() function.
Next, Y splits the_values into its component parts, loading "name:thau"
into separated_values[0], "age:just a tyke" into separated_values[1], and
"phone:411" into separated_values[2].
After the function breaks up the_values, Z loops through each of the
three elements (name, age, and phone) in separated_values. Each time through
the loop, the function breaks the element into two pieces along the colon. It
then loads the first part of the element into the_property and the second part
into the_value.
The first time through the loop, the_property is "name" and the_value
is "thau". Once the element is split like this, the associative array the_info
gets loaded in [. After the loop has occurred three times, you get these
results: the_info["name"] = "thau", the_info["age"] = "just a tyke", and
the_info["phone"] = "411".
With the associative array loaded properly, the three lines starting in _
retrieve the information and display it on a web page.
Setting the Duration of a Cookie
Until now, we’ve been creating cookies that disappear when a user exits the
browser. Sometimes this is for the best. Since each domain can have only 20
cookies on a user’s machine, you don’t want to waste space by saving unnecessary cookies between browser sessions. However, if you do want your cookies
to remain on a user’s hard drive after he or she quits the browser, you have to
set an expiration date in UTC format. For example,
Sun, 12 Jan 1992 00:00:00 UTC
is the supposed birth date in of HAL 9000, the intelligent computer from
2001: A Space Odyssey, expressed in UTC. (“HAL? HAL? Are you out there?”)
NOTE UTC time is the time at the Royal Observatory in Greenwich, England. Urbana,
Illinois, where HAL was built, is six hours west of Greenwich, so the date given
here is actually 6 PM local time on January 11.
Saving Visitor Information with Cookies 223
The UTC format can be sort of a pain, especially since you must figure
out whether the day was a Monday, Friday, or whatever. Luckily, JavaScript’s
toUTCString() date method converts a date in a simpler format to a date in
UTC format. Here’s an easy way to set a date relatively far into the future:
var the_date = new Date("December 21, 2012");
var the_cookie_date = the_date.toUTCString();
NOTE JavaScript versions earlier than 1.3 used a date string format in which the day, month,
and year were separated by hyphens instead of spaces, and the time was followed by the
letters GMT to indicate that it was Greenwich Mean Time. This was therefore called
GMT format, and JavaScript had a toGMTString() method instead of a toUTCString()
method. The toGMTString() method is still provided, but UTC is the norm. For example,
with Windows XP and Internet Explorer 6.0, toGMTString() returns a UTC string,
and new Date() works when passed a UTC string but not when passed a GMT string.
To set your cookie to expire, you have to add the expiration date to the
cookie. Add expires = date to the string, and separate the cookie components
with a semicolon:
cookie_name = whatever;expires = date
Figure 12-7 shows you how to build a cookie that will last until the end of
the Mayan calendar:
function setCookie()
{
// get the information
//
var the_name = prompt("What's your name?","");
var the_date = new Date("December 21, 2012");
var the_cookie_date = the_date.toUTCString();
// build and save the cookie
//
var the_cookie = "my_cookie=" + escape(the_name);
the_cookie = the_cookie + ";expires = " + the_cookie_date;
document.cookie = the_cookie;
}
Figure 12-7: Setting a cookie that will expire far in the future
Before the_cookie in Figure 12-7 is escaped (using the escape() function),
it will resemble the following line:
my_cookie = thau;expires = Fri, 21 Dec 2012 00:00:00 UTC
Once set, this cookie lives on your visitor’s hard drive until the expiration date.
224 Chapter 12
You can also use the expiration date to delete cookies. To do so, set the
date to a time in the past. This can come in handy if you’re using cookies to
log people in and out of your site. When a visitor logs in, assign a cookie that
shows that the visitor has done so. When the user wants to log out, delete the
cookie.
Who Can Read the Cookie?
I’ve already mentioned that only the website that set a cookie can read it—
McDonald’s can’t read Burger King’s cookies, and vice versa. The full story is
a little more complicated than that, however.
Letting One Page Read a Cookie Set on Another
By default, only the web page that set the cookie can read it. If one of your
pages sets a cookie, to let other pages on your site read that cookie you must
set its path. The cookie’s path sets the top-level directory from which a cookie
can be read. Setting the path of a cookie to the root-level directory of your
site makes it possible for all your web pages to read the cookie.
To do this, add path=/; to your cookie. If you just want the cookie to be
readable in a directory called food, add path=/food;.
Dealing with Multiple Domains
Some websites have lots of little domains. For example, the Yahoo! web
portal has a main site (http://www.yahoo.com), a finance site (http://
finance.yahoo.com), a personalized site (http://my.yahoo.com), and many
others. By default, if a web page on the finance site sets a cookie, pages on
the personalized site can’t read that cookie. But if you add domain=domain_name
to a cookie, all domains ending in domain_name can read the cookie. To allow
all the web pages on any of the machines in the yahoo.com domain to read a
cookie, Yahoo! has to add domain=yahoo.com to the cookie.
The Whole Cookie
Adding an expiration date, domain, and path to a cookie makes it pretty big.
Figure 12-8 lists a function that sets all these variables so you can see the whole
picture in one example.
function setCookie()
{
var the_name = prompt("What's your name?","");
var the_date = new Date("December 21, 2012");
var the_cookie = escape(the_name) + ";";
var the_cookie = the_cookie + "path=/;";
var the_cookie = the_cookie + "domain=nostarch.com;";
var the_cookie = the_cookie + "expires=" + the_date.toUTCString() + ";";
document.cookie = "my_cookie=" + the_cookie;
}
Figure 12-8: Setting all the cookie properties
Saving Visitor Information with Cookies 225
Figure 12-8 results in a cookie that looks like this (before escaping it):
my_cookie = thau;path=/;domain = nostarch.com;expires =
Fri, 21 Dec 2012 00:00:00 UTC;
Of course, because I’m setting the domain to nostarch.com, only a web page
from a No Starch Press computer can read this cookie.
Setting Multiple Cookies
Sometimes one cookie just isn’t enough. For instance, if your website has
two different JavaScript applications—one that uses cookies to store information about your visitors and one that uses cookies to keep track of their
purchases—you’ll probably want to store these two types of information in
different cookies.
To save multiple cookies, just give each cookie a different name. Setting
document.cookie to a cookie with a new name won’t delete the cookies that are
already there. Here’s some code that sets two cookies:
var visitor_cookie = "this_person=" +
escape("name:thau/occupation:slacker/phone:411");
document.cookie = visitor_cookie;
var purchase_cookie = "purchases=" + escape("tshirt:1/furbie:15/burrito:400");
document.cookie = purchase_cookie;
This code sets document.cookie twice. It looks as if the second document.cookie =
statement should overwrite the information stored by the first one, as would
happen if some other object were to the left of the equal sign. Assignment to
document.cookie works differently, however. As long as the cookies have different names, you can store both in document.cookie. After running the lines
above, document.cookie looks like this (except for the escaped characters):
this_person = name:thau/occupation:slacker/phone:411;purchases=tshirt:1/
furbie:15/burrito:400
In this example, storing two cookies in document.cookie works well
because the JavaScript that looks at purchase information doesn’t have to
deal with the information in the other cookie. Unfortunately, it’s a bit difficult
to pull the contents of one cookie out of document.cookie because it contains
multiple cookies. Here’s where prewritten JavaScript libraries come in handy.
Cookie Libraries
You’ll find many free cookie libraries on the Web. Just use any search
engine, and search for javascript cookie to get a list. The functions in the
libraries generally come ready to run, so you can just cut and paste them
into your web pages. Webmonkey has exceptionally well-commented
libraries, so we’ll use its code here. You can find more of Webmonkey’s free
226 Chapter 12
JavaScript code at http://webmonkey.wired.com/webmonkey/reference/
javascript_code_library/wm_ckie_lib/?tw=reference&category=forms_data.
Figure 12-9 shows you Webmonkey’s code for accessing one cookie when
document.cookie is storing multiple cookies.
function WM_readCookie(name) {
if(document.cookie == '') { // there's no cookie, so return false
return false;
} else { // there is a cookie
var firstChar, lastChar;
var theBigCookie = document.cookie;
firstChar = theBigCookie.indexOf(name);// find the start of 'name'
var NN2Hack = firstChar + name.length;
{ // if you found the cookie
if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '='))
firstChar += name.length + 1; // skip 'name' and '='
// find the end of the value string (the next ';').
lastChar = theBigCookie.indexOf(';', firstChar);
if(lastChar == -1) lastChar = theBigCookie.length;
return unescape(theBigCookie.substring(firstChar, lastChar));
} else { // if there was no cookie of that name, return false
return false;
}
}
} // WM_readCookie
Figure 12-9: Reading one cookie from document.cookie
To use these functions, cut and paste them into the page, and call the
functions appropriately. To retrieve a cookie named thisuser, call the function WM_readCookie("thisuser").
Webmonkey’s well-commented functions speak for themselves. If you use
these, read them over first and make sure you understand how they work.
A Cookie-Based Shopping Cart
You can build fairly complicated applications using cookies. This section
discusses code that represents the start of a shopping cart script. You definitely do not want to use this code to run your own shopping cart—it’s much
too simplistic. For example, you can’t remove an item from the basket once
you’ve selected it.
However, this code should give you an idea of how to start building
complex applications using cookies. Figure 12-10 shows you the code for a
main page of a simple shopping cart (see Figure 12-11) with simple links to
pages that contain items to buy.
<html><head><title>Welcome to My Store</title>
</head>
<body>
<h1>Welcome to My Store!</h1>
Here you can buy:<br>