Java Reference
In-Depth Information
For example, take the first line where you use the
setCookie()
function. Here you are setting a cookie
that will be named
Name
and have the value
Bob
. You don't want to set the
path
or
expires
parts, so
you omit those parameters.
The remaining two lines in the previous code snippet set the cookies named
Age
and
FirstVisit
and
set their values to
101
and
10 May 2007
, respectively.
If you did want to set the path and the expiration date, how might you change your code?
Well, imagine that you want the path to be
/MyStore
and the expiration date to be one year in the
future. Then you can use the
setCookie()
function in the following way:
var expires = new Date();
expires.setMonth(expires.getMonth() + 12);
setCookie("Name","Bob","/MyStore", expires.toUTCString());
First, you create a new
Date
object, and by passing no parameter to its constructor, you let it initialize
itself to the current date. In the next line, you add 12 months to that date. When setting the cookie
using
setCookie()
you pass
"/MyStore"
as the path and
expires.toUTCString()
as the expires
parameter.
What about the situation in which you've created your cookie, say, one named
Name
with a value of
Bob
, and you want to change its value? To do this, you can simply set the same cookie again, but with
the new value. To change the cookie named
Name
from a value of
Bob
to a value of
Bobby
, you'd need
the following code:
setCookie("Name","Bobby");
What if you want to delete an existing cookie? Well, that's easy. Just make it expire by
changing its value and setting its expiration date to a date in the past, as in the following example:
setCookie("Name","","","Mon, 1 Jan 1990 00:00:00");
getting a Cookie's Value
In the preceding example, you used
document.cookie
to retrieve a string containing information
about the cookies that have been set. However, this string has two limitations:
➤
The cookies are retrieved in name/value pairs, with each individual cookie separated by a
semicolon. The
expires
,
path
,
domain
, and
secure
parts of the cookie are not available to
you and cannot be retrieved.
➤
The
cookie
property enables you to retrieve only
all
the cookies set for a particular path
and, when they are hosted on a web server, that web server. So, for example, there's no
simple way of just getting the value of a cookie with the name
Age
. To do this you'll have
to use the string manipulation techniques you learned in previous chapters to cut the
information you want out of the returned string.