JS call cookie

Source: Internet
Author: User

 

The document object has a cookie attribute. But what is Cookie? "Some websites store some information on your hard disk with small text files, which are called cookies ." -- MSIE help. In general, cookies are created by CGI or similar files and programs that are more advanced than HTML, but JavaScript also provides comprehensive access rights to cookies.

Before continuing, we must first learnBasic cookie knowledge.

Each cookie is like this: <cookie name >=< value>

The <cookie Name> restriction is similar to the Javascript naming restriction, with the addition of "cannot use JavaScript keywords" and "can only use characters that can be used in URL encoding" missing ". The latter is hard to understand, but as long as you only use letters and numbers for naming, there is no problem at all. The <value> requirement is "only characters that can be used in URL encoding ".

Each Cookie has an expiration date. Once the computer clock expires, the cookie will be deleted. You cannot delete a cookie directly, but you can delete it indirectly by setting the expiration date earlier than the current time.

Each webpage, or site, has its own cookies. These cookies can only be accessed by webpages under the site, from webpages in other sites or in unauthorized areas under the same site, is inaccessible. Each "group" Cookie has a specified total size (about 2 kb per "group"). If the total size exceeds the maximum size, the first invalid cookie is deleted first, to make the new cookie "home ".

Now let's learnUse document. Cookie attributes
.

If you directly use document. cookie attribute, or use a method such as assigning values to variables to obtain the document. cookie value, we can know the number of cookies in the current document, the name of each cookie, and its value. For example, add "document. Write (document. Cookie)" to a document. The result is as follows:

Name = Kevin; email = kevin@kevin.com; lastvisited=index.html

This means that the document contains three cookies: name, email, and lastvisited, whose values are Kevin, kevin@kevin.com, and index.html. We can see that two cookies are separated by semicolons and spaces, so we can use cookiestring. the split (';') method returns an array separated by each cookie (VAR cookiestring = document first. cookie ).

To set a cookie, assign a value to document. Cookie. Unlike other conditions, assigning values to document. Cookie does not delete the original cookies, but only adds or modifies the original cookies. Assignment format:

Document. Cookie ='Cookiename= '+
Escape ('Cookievalue')
+ '; Expires =' +Expirationdateobj. Togmtstring ();

Are you dizzy? The above is not the place where the bold text is to be copied without mistake, the bold text is to be changed according to the actual situation. Cookiename indicates the cookie name, cookievalue indicates the cookie value, and expirationdateobj indicates the date object name storing the expiration date. If you do not need to specify the expiration date, the second row is not required. If no expiration date is specified, the browser expires after the browser is closed (that is, all windows are closed) by default.

Have you seen the underline above? These are important points.
First, the escape () method: Why must it be used? Because the cookie value must be "only characters that can be used in URL encoding ". We know that the "escape ()" method is to encode the string by URL encoding, then we only need to use an "escape ()" method to process the value output to the cookie, you can use "scape SCAPE ()" to process the values received from cookies. The most common use of these two methods is to process cookies. In fact, setting a cookie is as simple as "document. Cookie = 'cookiename = cookievalue '", but to avoid
It is better to use an escape () if the cookievalue contains characters not allowed in the URL.
Then the semicolon before "expires" is noted. It is a semicolon rather than a semicolon.
Finally, togmtstring () method: Set the Cookie's validity period date to use the GMT format, and other formats of time do not work.

Now let's take a look. Set a cookie named "name = rose" and expire three months later.

VaR expires = new date ();
Expires. settime (expires. gettime () + 3*30*24*60*60*1000 );
/* Three months x one month treated as 30 days x 24 hours a day
X hour 60 Minutes x minute 60 seconds x second 1000 ms */
Document. Cookie = 'name = rose; expires = '+ expires. togmtstring ();

Why not use the escape () method? This is because we know that Rose is a legal URL encoded string, that is, 'Rose '= escape ('Rose '). Generally, if you do not use escape () when setting a cookie, you do not need to use Unescape () when obtaining the cookie ().

Next time: Write a function to find the value of the specified cookie.

Function getcookie (cookiename ){
VaR cookiestring = Document. Cookie;
VaR start = cookiestring. indexof (cookiename + '= ');
// The reason for adding the equal sign is to avoid having
// The same string as cookiename.
If (START =-1) // cannot be found
Return NULL;
Start + = cookiename. Length + 1;
VaR end = cookiestring. indexof (';', start );
If (END =-1) return Unescape (cookiestring. substring (start ));
Return Unescape (cookiestring. substring (START, end ));
}

This function uses some methods of the string object. If you do not remember (Are you so unremembered), please check it out. All the IF Statements of this function do not contain the else. This is because if the condition is true, the program runs the return statement, and the operation stops when the return statement is run in the function, so it's okay if you don't add Else. When this function finds the cookie, it will return the cookie value; otherwise, "null" is returned ".

Now we want to delete the name = rose cookie we just set.

VaR expires = new date ();
Expires. settime (expires. gettime ()-1 );
Document. Cookie = 'name = rose; expires = '+ expires. togmtstring ();

As you can see, you only need to change the expiration date to a little earlier than the current date (this is 1 millisecond earlier), and then set the cookie in the same way to delete the cookie.

 

 

 

Setcookie: function (name, value)

{Document. Cookie = Name + "=" + value ;},

Getcookie: function (name)

{Var strcookie = Document. Cookie; var arrcookie = strcookie. Split (";");

For (VAR I = 0; I <arrcookie. length; I ++) {var arr = arrcookie [I]. Split ("= ");

If (! Arr [1]) {return "" ;}if (ARR [0] == name) {return arr [1] ;}} return "";},

Delcookie: function (name)

{Var exp = new date (); exp. settime (exp. gettime ()-1); var cval = This. getcookie (name );

If (cval! = NULL) document. Cookie = Name + "=" + cval + "; expires =" + exp. togmtstring ();}

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.