Creating Cookies


One of the most powerful document object properties is the cookie property, which enables you to set and read cookies. We'll see how to use cookies in Chapter 23, "Cookies and Creating Your Own Objects," but here's a preview. The cookie property holds the text of the cookies in the computer, so you give your cookie a name ; I'll just use cookie1 here, and give it an expiration date of one day. When the user clicks a button, the code will set a cookie with the text "Here is the cookie text.", and when the user clicks another button, the code retrieves that cookie's text and displays it. Here's the codesee Chapter 23 for the details on working with cookies:

(Listing 09-03.html on the web site)
 <HTML>      <HEAD>          <TITLE>Working With Cookies</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function setCookieText()   {   var date1 = new Date()   date1.setTime(date1.getTime() + 24 * 60 * 60 * 1000)   document.cookie = "cookie1=Here is the cookie text.;expires="   + date1.toGMTString()   }   function getCookieText()   {   var cookieData = new String(document.cookie)   var cookieHeader = "cookie1="   var cookieStart = cookieData.indexOf(cookieHeader)   if (cookieStart != -1){   document.form1.text1.value = cookieData.substring(cookieStart   + cookieHeader.length)   }   else{   document.form1.text1.value = "Could not find the cookie."   }   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Working With Cookies</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" SIZE="40">              <BR>              <INPUT TYPE="BUTTON" VALUE="Create a cookie" ONCLICK="setCookieText()">              <BR>              <INPUT TYPE = BUTTON Value = "Retrieve cookie data"                 ONCLICK="getCookieText()">          </FORM>      </BODY>  </HTML> 

You can see the results in Figure 9.3, where I've created a cookie and then retrieved its text. That's just an appetizermore on cookies is coming up in Chapter 23.

Figure 9.3. Setting and retrieving a cookie.

graphics/09fig03.gif



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