This article mainly introduces how to obtain and delete JavaScript cookies. For more information, see
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. However, it is different from a general attribute. changing its value assignment does not mean losing the original value. For example, you can execute the following two statements 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 is obtained.
A similar method can be used to obtain the values 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:
The Code is as follows:
<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:
The Code is as follows:
<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 accessed by 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 and reuse the 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 expiration time is not set when the expireHours is set to 0, that is, the cookie disappears automatically when the browser is disabled. The function is implemented as follows:
The Code is 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:
The Code 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:
The Code 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>
You can also use another method that is circulating on the Internet:
The Code is as follows:
<Script language = "JavaScript" type = "text/JavaScript">
Function SetCookie (name, value) // two parameters: one is the name of the cookie and the other is the value.
{
Var Days = 30; // This cookie will be saved for 30 Days
Var exp = new Date (); // new Date ("December 31,999 8 ");
Exp. setTime (exp. getTime () + Days x 24x60*60*1000 );
Document. cookie = name + "=" + escape (value) + "; expires =" + exp. toGMTString ();
}
Function getCookie (name) // The cookie function.
{
Var arr = document. cookie. match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $ )"));
If (arr! = Null) return unescape (arr [2]); return null;
}
Function delCookie (name) // delete a cookie
{
Var exp = new Date ();
Exp. setTime (exp. getTime ()-1 );
Var cval = getCookie (name );
If (cval! = Null) document. cookie = name + "=" + cval + "; expires =" + exp. toGMTString ();
}
SetCookie ("xiaoqi", "3 ")
Alert (getCookie ('xiaoqi '));
</Script>