Creating Cookies


In this case, I'll create an example that will enable us to store a cookie, retrieve it, and delete it. With a great burst of originality, I'll call this cookie cookie1 , and give it the text Here is the cookie data! . To set this cookie, I'll create a function named setCookie , and just assign the cookie data pair to document.cookie :

 function setCookie()  {      document.cookie =          "cookie1=Here is the cookie data!;"          .          .          .  } 

Now when I want to search for the cookie's data (as when the page is reloaded later), all I have to do is to search the document.cookie for cookie1= , and I know that the data for that cookie follows .

In fact, it's rare that you set a cookie this way, because it'll expire as soon as the browser closes . Instead, you usually set an expiration date yourself using an expires =date; pair. For example, I can make the cookie expire in 24 hours by adding 24 * 60 * 60 * 1000 milliseconds to the current time and setting that as the expiration date (after converting it to GMT time with the toGMTString method). Here's how that looks in code. Note that I'm also displaying an alert box to indicate that the cookie has been created:

 function setCookie()  {  var cookieDate = new Date()   cookieDate.setTime(cookieDate.getTime() + 24 * 60 * 60 *   1000)   document.cookie =   "cookie1=Here is the cookie data!;expires="   + cookieDate.toGMTString()   alert("Cookie created!")  } 

Here's an example that uses this code to set cookie1 when the user clicks a button:

(Listing 23-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With Cookies          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function setCookie()   {   var cookieDate = new Date()   cookieDate.setTime(cookieDate.getTime() + 24 * 60 * 60 *   1000)   document.cookie =   "cookie1=Here is the cookie data!;expires="   + cookieDate.toGMTString()   alert("Cookie created!")   }  //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>              Working With Cookies          </H1>          <FORM NAME="form1">              <INPUT TYPE = BUTTON Value = "Create the cookie"                  ONCLICK = "setCookie()">          </FORM>      </BODY>  </HTML> 

You can see the results in Figure 23.1, where I've clicked the button and created the cookie.

Figure 23.1. Creating a cookie.

graphics/23fig01.gif

The next step is to read the cookie data back in, and I'll take a look at that now.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net