This article mainly introduces detailed Document. cookie-related information. For more information, see the cookie mechanism. The Cookie mechanism adopts the client-side persistence scheme, while the session mechanism adopts the server-side persistence scheme.
At the same time, we can also see that because the server-side persistence scheme also needs to save an identifier on the client, the session mechanism may need to use the cookie Mechanism to save the identifier, but in fact it has other options.
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%20love%20ajax";
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: