Document. Cookie,

Source: Internet
Author: User
Tags set cookie

Document. Cookie,

Specifically, 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:

  <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 cookie documents. 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>

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 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>

Ps: Jquery Cookie operation parameters:

Create a session cookie:

<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>

Note: When no cookie time is specified, the created cookie is valid until the user's browser is disabled by default. Therefore, it is called a session cookie.

Create a persistent cookie:

$.cookie(‘cookieName','cookieValue',{expires:7});

Note: when the time is specified, it is called a persistent cookie and the validity period is day.

Create a persistent cookie with a valid path:

$.cookie(‘cookieName','cookieValue',{expires:7,path:'/'});

Note: If you do not set a valid path, you can only read the cookie on the current page of the cookie setting by default. The cookie Path is used to set the top-level directory that can read the cookie.

Create a persistent cookie with valid path and Domain Name:

$.cookie(‘cookieName','cookieValue',{expires:7,path:'/',domain: ‘chuhoo.com',secure: false,raw:false});

Note: domain: the domain Name of the webpage where the cookie is created; secure: The default value is false. If it is true, the cookie transmission protocol must be https; raw: The default value is false, this function is automatically encoded and decoded during reading and writing (encodeURIComponent encoding and decodeURIComponent decoding). disable this function and set it to true.

Get cookie:

$. Cookie ('cookiename'); // if it exists, cookieValue is returned; otherwise, null is returned.

Delete cookie:

$.cookie(‘cookieName',null);

Note: To delete a cookie with a valid path, as follows: $. cookie ('cookiename', null, {path :'/'});

Articles you may be interested in:
  • Use javascript For document. cookie
  • Use javascript For document. cookie

Related Article

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.