JavaScript Introductory Tutorials Cookies_ Basics

Source: Internet
Author: User
Some WEB sites store information in small text files on your hard disk, which are called cookies. "--msie help. In general, cookies are CGI or similar, created in a way that is more than HTML advanced files, programs, and so on, but JavaScript also provides a full range of access rights to cookies.
Before we go on, we'll learn the basics of cookies.
This is true for each Cookie: <cookie name >=< value >
<cookie name > Restrictions are much the same as JavaScript naming restrictions, with fewer "JavaScript keywords" and "only characters that can be used in URL encoding". The latter is more difficult to understand, but as long as you name only letters and numbers, there is no problem at all. The < value > requirement is also "use only characters that can be used in URL encoding."
Each cookie has a expiration date, and once the computer's clock expires, the cookie is deleted. We can't delete a Cookie directly, but we can delete it indirectly by setting the expiration date earlier than the present time.
Each Web page, or every site, has its own cookies, which can only be accessed by pages under this site, and pages from other sites or unauthorized areas under the same site are inaccessible. Each "group" of cookies has the specified total size (about 2KB per "group"), one exceeds the maximum total size, the first expired cookies are deleted first, to let the new cookie "home".
Now let's learn to use the Document.cookie attribute.
If you use the Document.cookie property directly, or, for example, assign a value to a variable to get the value of a document.cookie, we know how many cookies are in the current document, the name of each cookie, and its value. For example, adding "document.write (document.cookie)" To a document shows:
Copy Code code as follows:

Name=kevin; email=kevin@kevin.com; Lastvisited=index.html

This means that the document contains 3 Cookies:name, email and lastvisited, and their values are Kevin, kevin@kevin.com and Index.html respectively. As you can see, two Cookies are separated by semicolons and spaces, so we can use Cookiestring.split ('; ') method to get a separate array of each Cookie (first with var cookiestring = Document.cookie).
The way to set a Cookie is to assign a value to the Document.cookie. Unlike other assignments, assigning a value to a document.cookie does not delete the original cookies, but only adds cookies or changes the original cookie. The format of the assignment:
Copy Code code as follows:

Document.cookie = ' cookiename= ' + Escape (' Cookievalue ')
+ '; expires= ' + expirationdateobj.togmtstring ();

Do you see dizziness? The above is not a bold word place is to copy not mistaken, bold word is to be changed according to the actual situation. CookieName represents the name of the cookie, Cookievalue represents the value of the cookie, Expirationdateobj represents the Date object name for which the expiration date is stored, and if no expiration date is required, the second row is not required. Does not specify a expiration date, the browser defaults to expire after the browser is closed (that is, all windows are closed).
Do you see some underscores on the top? These are the places to be noted.
First Escape () method: Why must use? Because the value of a Cookie requires "only characters that can be used in URL encoding." We know that the "escape ()" method is to encode the string by the URL encoding method, so we only need to use an "escape ()" method to process the value of the output to the cookie, "unescape ()" To handle the value received from the cookie is foolproof. And the most common use of these two methods is to process Cookies. In fact, setting a Cookie is just "document.cookie = ' cookiename=cookievalue '" as simple as this, but in order to avoid the characters that are not allowed to appear in the URL in Cookievalue, use an escape ().
Then the semicolon before "expires": just notice. Is the semicolon, not the other.
Finally toGMTString () method: Set the time limit of the Cookie is in GMT format, the other format time is not useful.
Now let's do some real combat. Set a "Name=rose" Cookie that expires after 3 months.
Copy Code code as follows:

var expires = new Date ();
Expires.settime (Expires.gettime () + 3 * 30 * 24 * 60 * 60 * 1000);
* * Three months x one months as 30 days x 24 hours a day
X one hour, 60 minutes, x 60 seconds, 1000 milliseconds a second.
Document.cookie = ' name=rose;expires= ' + expires.togmtstring ();

Why not use the Escape () method? This is because we know that Rose is a legitimate URL-coded string, which means ' rose ' = Escape (' Rose '). In general, if you set a cookie without escape (), you do not need to unescape () to get the cookie.
One more time: Write a function that looks for the value of the specified Cookie.
Copy Code code as follows:

function GetCookie (cookiename) {
var cookiestring = Document.cookie;
var start = Cookiestring.indexof (cookiename + ' = ');
The reason to add an equal sign is to avoid the value of some cookies
The same string as CookieName.
if (start = = 1)//not 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 of the methods of the string object, if you don't remember (you're not so forgetful), please check it out quickly. This function all if statements are not brought else, this is because if the condition is set up, the program is running a return statement, in the function hit return, it will terminate the operation, so do not add else also no problem. When the function finds a cookie, it returns the value of the cookie, otherwise it returns "null."
Now we want to remove the name=rose Cookie that we just set.
Copy Code code as follows:

var expires = new Date ();
Expires.settime (Expires.gettime ()-1);
Document.cookie = ' name=rose;expires= ' + expires.togmtstring ();

As you can see, you can delete cookies by simply changing the expiration date to one o'clock (1 milliseconds earlier) and then setting the cookie in the same way.

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.