Detailed Document.cookie_javascript Skills

Source: Internet
Author: User
Tags current time

Specifically, the cookie mechanism is a scheme for maintaining state on the client side, and the session mechanism uses the scheme of maintaining state at the server end.

At the same time, we also see that because the server-side retention scheme also needs to be stored in the client, the session mechanism may need to use the cookie mechanism to save the identity, but in fact it has other options.

Set cookies

Each cookie is a name/value pair, and you can assign a string such as the following to Document.cookie:

Document.cookie= "userid=828";

If you want to store more than one name/value pair at a time, you can use a semicolon plus a space (;) to separate it, for example:

Document.cookie= "userid=828; Username=hulk ";

You cannot use semicolons (;), commas (,), Equals (=), and spaces in the name or value of a cookie. It is easy to do this in the name of a cookie, but the value to be saved is indeterminate. How do you store these values? The method is encoded with the escape () function, which can be used to represent some special symbols in hexadecimal notation, such as "20%", which can be stored in cookie values, and can be used to avoid the appearance of garbled Chinese. For example:

Document.cookie= "str=" +escape ("I love Ajax");

Equivalent:

  Document.cookie= "Str=i%20love%20ajax";

When you use Escape () encoding, you need to use unescape () to decode after the value is fetched to get the original cookie value, as described earlier in this article.

Although Document.cookie looks like an attribute, it can be assigned a different value. However, unlike the general properties, changing its assignment does not mean losing the original value, such as executing the following two statements consecutively:

Document.cookie= "userid=828";
  Document.cookie= "Username=hulk";

The browser will maintain two cookies, respectively UserID and username, so give the document.cookie a value like executing a statement similar to this:

Document.addcookie ("userid=828");
  Document.addcookie ("Username=hulk");

In fact, the browser is the way to set cookies, if you want to change the value of a cookie, you just have to reassign the value, for example:

 Document.cookie= "userid=929";

This sets the cookie value named UserID to 929.

Get the value of a cookie

The following describes how to get the value of a cookie. The value of a cookie can be obtained directly by Document.cookie:

var Strcookie=document.cookie;

This will get a string of multiple name/value pairs separated by semicolons that include all cookies under that 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 cookie value for the output. This shows that you can only get all the cookie values at once, not the cookie name to get the specified value, which is the most troublesome part of handling the cookie value. The user must parse this string himself to get the specified cookie value, for example, to get the value of the UserID, which can be achieved by:

 <script language= "JavaScript" type= "Text/javascript" >
  <!--
  //Set two cookies
  document.cookie= " userid=828 ";
  Document.cookie= "Username=hulk";
  Gets the cookie string
  var Strcookie=document.cookie;
  Cut multiple cookies to multiple name/value pairs
  var arrcookie=strcookie.split ("; ");
  var userId;
  Iterate through the cookie array, processing each cookie for the for
  (Var i=0;i<arrcookie.length;i++) {
  var arr=arrcookie[i].split ("=");
  //Find a cookie with the name UserId and return its value
  if ("UserId" ==arr[0]) {
  userid=arr[1];
  break;
  }
  }
  alert (userId);
  //-->
  </script>

In this way, you get the value of a single cookie in a similar way, you can get the value of one or more cookies, and the main trick is still the operation of strings and arrays.

Set expiration date for cookie

Until now, all cookies are a single session cookie, that is, the cookies will be lost after the browser is closed, in fact these cookies are only stored in memory, but not the corresponding hard disk files.

In actual development, cookies often need to be saved for long periods of time, such as saving the user's login status. This can be accomplished with the following options:

Document.cookie= "userid=828; Expires=gmt_string ";

Where Gmt_string is a time string in GMT format, this statement is to set the UserID cookie to the expiration time that gmt_string represents, over which the cookie disappears and is 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" >
  <!--
  //Get current time
  var date=new date ();
  var expiredays=10;
  Set date to 10 days after
  Date.settime (Date.gettime () +expiredays*24*3600*1000);
  Set the UserId and userName two cookies to expire 10 days later
  document.cookie= "userid=828 username=hulk; expire=" +date.togmtstring ();
  //-->
  </script>
 
  Delete cookies to
 
  delete a cookie, you can set its expiration time to a past time, for example:
 
  <script Language= "JavaScript" type= "Text/javascript" >
  <!--
  //Get current time
  var date=new date ();
  Set date to past time
  Date.settime (Date.gettime () -10000);
  //delete userId this cookie
  document.cookie= "userid= 828; Expire= "+date.togmtstring ();
  //-->
  </script>

Ps:jquery Cookie's operation parameters:

Create a session Cookie:

 <script language= "JavaScript" type= "Text/javascript" >
<!--
//Get current time
var date=new date ();
var expiredays=10;
Set date to 10 days after
Date.settime (Date.gettime () +expiredays*24*3600*1000);
Set the UserId and userName two cookies to expire 10 days later
document.cookie= "userid=828 username=hulk; expire=" +date.togmtstring ();
//-->
</script>

Delete cookies to

delete a cookie, you can set its expiration time to a past time, for example:

<script Language= "JavaScript" type= "Text/javascript" >
<!--
//Get current time
var date=new date ();
Set date to past time
Date.settime (Date.gettime () -10000);
//delete userId this cookie
document.cookie= "userid= 828; Expire= "+date.togmtstring ();
//-->
</script>

Note: When no cookie time is specified, the cookie that is created is known as the session cookie by default to the user's browser shutdown.

To create a persistent cookie:

$.cookie (' cookiename ', ' Cookievalue ', {expires:7});

Note: When the time is specified, it is called a persistent cookie and the valid time is days.

Create a cookie that is persistent and with a valid path:

$.cookie (' cookiename ', ' Cookievalue ', {expires:7,path: '/'});

Note: If you do not set a valid path, by default, only the path to read the Cookie,cookie on the cookie Settings current page is used to set up a top-level directory that can read cookies.

Create a cookie that is persistent and with a valid path and domain name:

$.cookie (' cookiename ', ' Cookievalue ', {expires:7,path: '/', Domain: ' chuhoo.com ', secure:false,raw:false});

Note: domain: Create the name of the Web page owned by the cookie; secure: Default is False, if the transport protocol for True,cookie is Https;raw: Default is False, Automatic encoding and decoding when reading and writing (using encodeURIComponent encoding, decoding using decodeuricomponent), turn off this feature, set to true.

Get cookies:

$.cookie (' cookiename '); Returns Cookievalue if present, otherwise null is returned.

To delete a cookie:

$.cookie (' cookiename ', null);

Note: If you want to delete a cookie with a valid path, the following: $.cookie (' CookieName ', Null,{path: '/'});

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.