Source: http://hi.baidu.com/225247/blog/item/3a1fff298b998cf899250a10.html
Set cookie
Each cookie is a name/value pair. You can assign the following string to document. COOKIE:
Document. Cookie = "userid = 828 ";
To store multiple name/value pairs at a time, use semicolons (;) to separate them. For example:
Document. Cookie = "userid = 828; username = hulk ";
The names or values of cookies cannot contain semicolons (;), commas (,), equal signs (=), and spaces. It is easy to do this in the cookie name, but the value to be saved is uncertain. How can we store these values? The method is encoded using the escape () function. It can represent some special symbols in hexadecimal notation. For example, spaces are encoded as "20%", which can be stored in cookie values, in addition, this solution can avoid Chinese garbled characters. For example:
Document. Cookie = "str =" + escape ("I love Ajax ");
Equivalent:
Document. Cookie = "str = I % 20 love % 20 Ajax ";
After escape () encoding is used, you must use Unescape () to decode the extracted value to obtain the original cookie value, which has been described earlier.
Although document. Cookie looks like an attribute, different values can be assigned. But it is different from the general property, changing
Its value assignment does not mean that the original value is lost. For example, the following two statements are executed consecutively:
Document. Cookie = "userid = 828 ";
Document. Cookie = "username = hulk ";
In this case, the browser will maintain two cookies, namely userid and username. Therefore, assigning a value to document. Cookie is more like executing a statement like this:
Document. addcookie ("userid = 828 ");
Document. addcookie ("username = hulk ");
In fact, the browser sets the cookie in this way. To change the value of a cookie, you only need to assign a value again. For example:
Document. Cookie = "userid = 929 ";
In this way, set the cookie value named userid to 929.
Obtain the cookie value.
The following describes how to obtain the cookie value. The cookie value can be directly obtained by document. COOKIE:
VaR strcookie = Document. Cookie;
This will obtain a string consisting of multiple name/value pairs separated by semicolons. These name/value pairs include all cookies under the domain name. For example:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
Document. Cookie = "userid = 828 ";
Document. Cookie = "username = hulk ";
VaR strcookie = Document. Cookie;
Alert (strcookie );
// -->
</SCRIPT>
Figure 7.1 shows the output cookie value. It can be seen that all cookie values can be obtained only once, but the cookie name cannot be specified to obtain the specified value, which is the most troublesome part of processing the cookie value. You must analyze this string to obtain the specified cookie value. For example, to obtain the userid value, you can do this:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
// Set two cookies
Document. Cookie = "userid = 828 ";
Document. Cookie = "username = hulk ";
// Obtain the cookie string
VaR strcookie = Document. Cookie;
// Cut multiple cookies into multiple name/value pairs
VaR arrcookie = strcookie. Split (";");
VaR userid;
// Traverse the cookie array to process each cookie pair
For (VAR I = 0; I <arrcookie. length; I ++ ){
VaR arr = arrcookie [I]. Split ("= ");
// Find the cookie named userid and return its value
If ("userid" = arr [0]) {
Userid = arr [1];
Break;
}
}
Alert (userid );
// -->
</SCRIPT>
In this way, the value of a single cookie can be obtained using a similar method to obtain the value of one or more cookies. The main technique is the operations related to strings and arrays.
Set the cookie end date
Until now, all cookies are single-session cookies, that is, these cookies will be lost after the browser is closed. In fact, these cookies are only stored in the memory, and no corresponding hard disk files are created.
In actual development, cookies often need to be saved for a long time, for example, the user login status. This can be achieved using the following options:
Document. Cookie = "userid = 828; expires = gmt_string ";
Gmt_string is a time string in GMT format. This statement sets the cookie userid to the expiration time indicated by gmt_string. After this time, the cookie disappears and becomes inaccessible. For example, if you want to set the cookie to expire after 10 days, you can do this:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
// Obtain the current time
VaR date = new date ();
VaR expiredays = 10;
// Set the date value to 10 days later.
Date. settime (date. gettime () + expiredays * 24*3600*1000 );
// Set the cookie userid and username to expire after 10 days
Document. Cookie = "userid = 828; username = Hulk; expire =" + date. togmtstring ();
// -->
</SCRIPT>
Delete cookie
To delete a cookie, you can set its expiration time to a previous time, for example:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
// Obtain the current time
VaR date = new date ();
// Set date to the past time
Date. settime (date. gettime ()-10000 );
// Delete the cookie userid
Document. Cookie = "userid = 828; expire =" + date. togmtstring ();
// -->
</SCRIPT>
Specify the path to the cookie
By default, if a cookie is created on a page, other pages in the directory where the page is located can also access the cookie. If there are subdirectories in this directory, they can also be accessed in the subdirectory. For example
Cookiecreated in www.xxxx.com/html/a.html can be www.xxxx.com/html/ B .htmlor
Www.xxx.com/html/Some/c.html, but cannot be accessed by www.xxxx.com/d.html.
To control the directories that can be accessed by cookies, you need to use the path parameter to set cookies. The syntax is as follows:
Document. Cookie = "name = value; Path = cookiedir ";
Cookiedir indicates the directory that can access cookies. For example:
Document. Cookie = "userid = 320; Path =/shop ";
Indicates that the current cookie can only be used in the shop directory.
To make the cookie available on the entire website, you can specify cookie_dir as the root directory. For example:
Document. Cookie = "userid = 320; Path = /";
Specifies the Host Name of the cookie that can be accessed.
Similar to the path, host names are different hosts in the same domain. For example, www.google.com and gmail.google.com are two different host names. By default, cookies created on one host cannot be accessed on the other, but can be controlled by the domain parameter. The syntax format is as follows:
Document. Cookie = "name = value; domain = cookiedomain ";
Take Google as an example. To achieve cross-host access, you can write as follows:
Document. Cookie = "name = value; domain = .google.com ";
In this way, all hosts under Google.com can access this cookie.
Comprehensive example: construct common cookie processing functions
Cookie processing is complex and has a certain degree of similarity. Therefore, you can define several functions to perform common cookie operations.Code. Common cookie operations and their function implementations are listed below.
1. Add a cookie: addcookie (name, value, expirehours)
This function receives three parameters: Cookie name, cookie value, and how many hours after expiration. The expirehours is
When the browser is disabled, the cookie disappears automatically. The function is implemented as follows:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
Function addcookie (name, value, expirehours ){
VaR cookiestring = Name + "=" + escape (value );
// Determine whether to set the expiration time
If (expirehours> 0 ){
VaR date = new date ();
Date. settime (date. gettime + expirehours * 3600*1000 );
Cookiestring = cookiestring + "; expire =" + date. togmtstring ();
}
Document. Cookie = cookiestring;
}
// -->
</SCRIPT>
2. Get the cookie value of the specified name: getcookie (name)
This function returns the cookie value named name. If it does not exist, it returns NULL. Its implementation is as follows:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
Function getcookie (name ){
VaR strcookie = Document. Cookie;
VaR arrcookie = strcookie. Split (";");
For (VAR I = 0; I <arrcookie. length; I ++ ){
VaR arr = arrcookie [I]. Split ("= ");
If (ARR [0] = Name) return arr [1];
}
Return "";
}
// -->
</SCRIPT>
3. Delete the cookie with the specified name: deletecookie (name)
This function can delete the cookie with the specified name. Its implementation is as follows:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
Function deletecookie (name ){
VaR date = new date ();
Date. settime (date. gettime ()-10000 );
Document. Cookie = Name + "= V; expire =" + date. togmtstring ();
}
// -->
</SCRIPT>
Function setcookie (name, value, x_expires, x_path, x_domain, x_secure ){
// Set a cookie value function
// Alert (name)
VaR argv = setcookie. arguments;
// Alert (this. argv );
VaR argc = setcookie. Arguments. length;
VaR expires
= (Argc> 2 )? X_expires: NULL;
VaR Path = (argc> 3 )? X_path:
NULL;
VaR domain = (argc> 4 )? X_domain: NULL;
VaR secure = (argc
> 5 )? X_secure: false;
Document. Cookie = Name + "=" + escape (value) +
(Expires = NULL )? "": ("; Expires =" + expires. togmtstring () +
(Path = NULL )? "": ("; Path =" + path) +
(Domain = NULL )? "":(";
Domain = "+ domain) +
(Secure = true )? "; Secure ":
"");
}
Function getcookie (name) {// read the cookie value function of the specified name
//
Alert (document. Cookie)
VaR Arg = Name + "= ";
VaR Alen = Arg. length;
VaR clen = Document. Cookie. length;
VaR I = 0;
While (I <
Clen)
{
VaR J = I + Alen;
If (document. Cookie. substring (I,
J) = Arg)
Return getcookieval (j );
I =
Document. Cookie. indexof (";", I );
If (I =-1) break;
I + = 2;
}
Return NULL;
}
Function getcookieval (offset ){
VaR endstr
= Document. Cookie. indexof (";", offset );
If (endstr =-1)
Endstr = Document. Cookie. length;
Return
Unescape (document. Cookie. substring (offset, endstr ));
}
Function
Deletecookie (name) {// Delete the cookie value function
VaR exp = new date ();
Exp. settime (exp. gettime ()-1 );
VaR cval = getcookie (name );
Document. Cookie = Name + "=" + cval + "; expires =" + exp. togmtstring ();
}