Javascript cookie is a convenient persistent data storage solution suitable for clients. Cookie is a list of name-value pairs separated by semicolons. The following describes three reusable cookie methods:
Function writecookie (name, value, days ){
// By default, there is no expiration so the cookie is temporary
VaR expires = "";
// Specifying a number of days makes the cookie persistent
If (days ){
VaR date = new date ();
Date. settime (date. gettime () + (days * 24x60*60*1000 ));
Expires = "; expires =" + date. togmtstring ();
}
// Set the cookie to the name, value, and expiration date
Document. Cookie = Name + "=" + escape (value) + expires + "; Path = /";
}
Function readcookie (name ){
// Find the specified cookie and return its value
VaR searchname = Name + "= ";
VaR cookies = Document. Cookie. Split (';');
For (VAR I = 0; I <cookies. length; I ++ ){
VaR c = Cookies [I];
While (C. charat (0) = '')
C = C. substring (1, C. Length );
If (C. indexof (searchname) = 0)
Return Unescape (C. substring (searchname. length, C. Length ));
}
Return NULL;
}
Function erasecookie (name ){
// Erase the specified cookie
Writecookie (name, "",-1 );
}
Note:
1. the cookie name value cannot contain semicolons (;), commas (,), equal signs (=), and spaces. This rule is easily guaranteed in name, but the value is hard to guarantee, therefore, the escape function is used for encoding and the special characters in value are expressed in hexadecimal notation. For example, the space is "20% ". Similarly, when reading the cookie value, use Unescape to decode it.
2. set cookie to use document. cookie = "... ", although a cookie looks like an attribute, it is different from a general attribute. changing its value assignment does not mean that the original value is lost, but a new cookie is added. to change the value assignment of a cookie, you only need to assign a value again.
Example:
Writecookie ("username", "test ");
Writecookie ("password", "111 ");
Two cookies are created here: username and password. If the password changes, for example, to "222", writecookie ("password", "222") overwrites the existing cookie value.
3. Delete the cookie. The expiration time of the cookie is set to the previous day, so the cookie does not exist.