JavaScript getting started Cookies

Source: Internet
Author: User

Some Web sites store some information with small text files on your hard disk. These files 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 should first learn the basic knowledge of cookies.
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 learn how to use the document. cookie attribute.
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:
Copy codeThe Code 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:
Copy codeThe Code is as follows:
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 just "document. cookie = 'cookiename = cookieValue '"is so simple, but it is better to use an escape () to avoid any characters in the URL in cookieValue.
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.
Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
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.
Copy codeThe Code is as follows:
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.

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.