Setting Cookies


document.cookie = "myLanguage=JavaScript"; 

Setting a cookie with JavaScript equals setting the cookie property of the document object. It is important to use the same format the HTTP protocol uses for sending a cookie to the client. For "regular cookies" (cookies without expiration dates or other restrictions, as detailed in the following phrases), the name and the value of the cookie have to be separated by an equal sign. The name of the cookie must not contain any special characters like spaces, semicolons, and whitespace; such special characters in the cookie value should be URL-encoded (for instance, a space character turns into %20, the hexadecimal representation of its ASCII value). The specification recommends the encoding, but does not prescribe it.

As the following listing shows, setting more than one cookie can be achieved by setting multiple values to document.cookie. Therefore, writing to document.cookie does not overwrite any previous cookies, but is just adding cookies. The only exception to this rule: If a cookie of the same name exists, the client tries to overwrite it.

Setting a Cookie with JavaScript (setcookie.html)

<script language="JavaScript"   type="text/javascript"> document.cookie = "myLanguage=JavaScript"; document.cookie =   "myOtherLanguage=PHP:%20Hypertext%20Preprocessor" </script> 

Figure 7.1 shows the result in the browser if it's configured to ask the user before setting a cookie.

Figure 7.1. The browser tries to set the cookie sent from JavaScript.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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