Java Reference
In-Depth Information
function setCookie (cookieName, cookieValue, cookiePath, cookieExpires)
{
cookieValue = escape(cookieValue);
if (cookieExpires == “”)
{
var nowDate = new Date();
nowDate.setMonth(nowDate.getMonth() + 6);
cookieExpires = nowDate.toGMTString();
}
if (cookiePath != “”)
{
cookiePath = “;Path=” + cookiePath;
}
document.cookie = cookieName + “=” + cookieValue +
“;expires=” + cookieExpires + cookiePath;
}
setCookie(“Name”,”Bob”,””,””);
setCookie(“Age”,”101”,””,””);
setCookie(“FirstVisit”,”10 May 2007”,””,””);
alert(document.cookie);
</script>
</head>
<body>
</body>
</html>
Save the example as
CreateCookie.htm
and load it into a web browser.
You'll see the alert box shown in Figure 11-12. Note that all three cookies are displayed as name/value
pairs separated from the others by semicolons, and also that the expiration date is not displayed. If you
had set the path parameter, this also would not have been displayed. The UserName cookie from a pre-
vious example is also displayed.
Figure 11-12
You've already seen how the setCookie() function works, so let's look at the three lines that use the
function to create three new cookies.
setCookie(“Name”,”Bob”,””,””);
setCookie(“Age”,”101”,””,””);
setCookie(“FirstVisit”,”10 May 2007”,””,””);
It is all fairly simple. The fi rst parameter is the name that you'll give the cookie. (You'll see shortly how
you can retrieve a value of a cookie based on the name you gave it.) It's important that the names you
use be only alphanumeric characters, with no spaces, punctuation, or special characters. Although you
can use cookie names with these characters, doing so is more complex and best avoided. Next you have