Detailed description of document. cookie in js

Source: Internet
Author: User
Tags set cookie

Set cookie. Each cookie is a name/value pair. You can assign the following string to document. cookie: document. cookie = "userId = 828"; if you want to store multiple name/value pairs at a time, you can 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. Example: document. cookie = "str =" + escape ("I love ajax"); equivalent to: document. cookie = "str = I % 20 love % 20 ajax"; When escape () is used for encoding, the original cookie value must be decoded using unescape () after the value is retrieved, this is already 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 maintains two cookies: userId and userName. Therefore. cookie assignment 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"; then, set the cookie value named userId to 929. The following describes how to obtain the cookie value. The cookie value can be set by document. cookie: var strCookie = document. cookie, which is a string consisting of multiple name/value pairs separated by semicolons. These name/value pairs include all cookies under the domain name. 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 cookiedocument. cookie = "userId = 828"; document. cookie = "userName = hulk"; // obtain the cookie string var strCookie = document. cookie; // cut multiple cookies into multiple names/value pairs var arrCookie = strCookie. split (";"); var userId; // traverses the cookie array and processes 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> to obtain the value of a single cookie. To obtain the values of one or more cookies. The main technique is the operations related to strings and arrays. When the end date is set for the cookie, 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, the corresponding hard disk file is not 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 in GMT_String format, after this time, the cookie will disappear and cannot be accessed. 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 the date value after 10 days. setTime (date. getTime () + expireDays * 24*3600*1000); // set the cookie userId and userName to expire the document after 10 days. cookie = "userId = 828; userName = hulk; expire =" + date. toGMTString (); // --> </script> delete a 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 date. setTime (date. getTime ()-10000); // Delete the cookie userId document. cookie = "userId = 828; expire =" + date. toGMTString (); // --> </script> specifies the path for cookie Access. 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 must use the path parameter to set cookies. The syntax is as follows: document. cookie = "name = value; path = cookieDir"; cookieDir indicates the directory where the cookie can be accessed. 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 =/"; the host name and path for cookie Access are similar. The host name refers to 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 document. cookie = "name = value; domain = cookieDomain"; take google as an example. To achieve cross-host access, you can write it as: document. cookie = "name = value; domain = .google.com"; in this way, all hosts under google.com can access this cookie. Comprehensive example: the process of constructing a common cookie processing function cookie is complicated 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. This 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 with the name. If it does not exist, it returns NULL. Its implementation is as follows: <script language = "JavaScript" type = "te Xt/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, which is implemented 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>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.