Use cookies in Javascript

Source: Internet
Author: User

There is a cookie in the Document Object.
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
CGI or similar files that are more advanced than HTML,ProgramBut
Javascript also provides comprehensive access to cookies.

Before continuing, we must first learnCookie
Basic knowledge

.

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

<Cookie Name> restrictions and JavaScript
The naming restrictions are similar.
Keyword ", more" can only be used in URLs
Characters in encoding ". 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 usable
Characters in URL encoding ".

Each cookie
There is an expiration date. Once the computer clock expires, this cookie
Will be deleted. We cannot delete
Cookie, but you can indirectly delete it by setting the expiration date earlier than the current time.

Each webpage or site has its own
Cookies
It can only be accessed by webpages under the site. webpages from other sites or from unauthorized regions under the same site cannot be accessed. Each "group" cookie
There is a specified total size (about 2 kb
Each "group"), if the maximum size is exceeded, the first cookie that is invalid.
The cookie is deleted first to allow the new cookie to be "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
Document. Cookie value, we can know how many
Cookies, 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. Their values are
Kevin, kevin@kevin.com and index.html. Two cookies are displayed.
They are separated by semicolons and spaces, so we can use cookiestring. Split (';
') Method to obtain an array separated by each cookie (first use VaR cookiestring =
Document. Cookie ).

The method for setting a cookie is
Assign values. Unlike other conditions
Assigning values does not delete the original cookies, but only adds cookies.
Or change the original cookie. 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 cookie
The value must be "only usable
Characters in URL encoding ". We know that the "escape ()" method is to press the string
URL
Encoding method, we only need to use an "escape ()" method to process the output
Cookie value. "Unescape ()" is used to process
The received value is safe. And the most common use of these two methods is processing.
Cookies. In fact, setting a cookie is as simple as "document. Cookie = 'cookiename = cookievalue '", but to avoid
The cookievalue contains characters that are not allowed in the URL. An escape () is used ()
Okay.

Then the semicolon before "expires" is noted. It is a semicolon rather than a semicolon.

Finally, togmtstring () method: Set the Cookie's validity period on GMT
The format of time, other formats of time does not work.

Now let's take a look. Set a "name = Rose"
Cookie, which expires 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 set
You do not need to use escape () when obtaining a cookie ().

Next time: Write a function to find 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
If statements are not included
Else. This is because if the condition is true, all programs run the return
Statement. If return is run in the function, the operation is terminated, so no else is added.
No problem. When this function finds the cookie, it will return the cookie
Otherwise, return "null ".

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 (here it is earlier
1 ms), and then set the cookie in the same way, you can 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.