Java Reference
In-Depth Information
For example, a space has the hexadecimal value
20
, and the
semicolon the value
3B
. So the following code produces the
output shown in Figure 13-16:
alert(escape("2001 a space odyssey;"));
You can see that each space has been converted to
%20
, the
%
indicating that it represents an escape or special character
rather than an actual character, and that
20
is the ASCII
value of the actual character. The semicolon has been converted to
%3B
, as you'd expect.
figure 13-16
As you see later, when retrieving cookie values you can use the
unescape()
function to convert from
the encoded version to plaintext.
Back to your function; next you have an
if
statement:
if (!expires) {
var now = new Date();
now.setMonth(now.getMonth() + 6);
expires = now.toUTCString();
}
This deals with the situation in which the
expires
parameter does not contain a usable value (either
by omitting it or passing an empty string
""
). Because most of the time you want a cookie to last
longer than the session it's created in, you set a default value for
expires
that is six months after the
current date.
Next, if a value has been passed to the function for the
path
parameter, you need to add that value
when you create the cookie. You simply put
"path="
in front of any value that has been passed in
the
path
parameter:
if (path) {
path = ";Path=" + path;
}
Finally, on the last line you actually create the cookie, putting together the
name
,
cvalue
,
expires
,
and
path
parts of the string:
document.cookie = name + "=" + value + ";expires=" + expires + path;
You'll be using the
setCookie()
function whenever you want to create a new cookie because
it makes setting a cookie easier than having to remember all the parts you want to set. More
important, it can be used to set the expiration date to a date six months ahead of the current
date.
For example, to use the function and set a cookie with default values for
expires
and
path
, you just
type the following:
setCookie("cookieName","cookieValue");