Home >Web Front-end >JS Tutorial >JavaScript Cookies_Basic Knowledge

JavaScript Cookies_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 19:06:32937browse

Using Cookies We already know that there is a cookie attribute in the document object. But what are cookies? "Some Web sites store information on your hard drive in small text files called cookies." - MSIE Help. Generally speaking, Cookies are created by CGI or similar files, programs, etc. that are more advanced than HTML, but JavaScript also provides very comprehensive access rights to Cookies.
Before continuing, we must first learn the basic knowledge of Cookies.
Each Cookie is like this: =
The restrictions of are similar to the naming restrictions of JavaScript. There is less "cannot use JavaScript keywords" and more "can only be used." Characters used in URL encoding". The latter is more difficult to understand, but as long as you just use letters and numbers for names, you'll be fine. The requirement for is also "can only use characters that can be used in URL encoding".
Each cookie has an expiration date. Once the computer clock passes the expiration date, the cookie will be deleted. We cannot delete a cookie directly, but we can delete it indirectly by setting the expiration date earlier than the current time.
Each web page, or each site, has its own Cookies. These Cookies can only be accessed by web pages under this site. Web pages from other sites or unauthorized areas under the same site cannot. accessed. Each "group" of Cookies has a specified total size (approximately 2KB per "group"). Once the maximum total size is exceeded, the earliest expired Cookie will be deleted first to allow the new Cookie to "settle in".
Now let’s learn to use the document.cookie attribute.
If you use the document.cookie attribute directly, or use some method, such as assigning a value to a variable, to get the value of document.cookie, we can know how many Cookies there are in the current document, and the value of each Cookie name, and its value. For example, adding "document.write(document.cookie)" to a document, the result shows:

name=kevin; email=kevin@kevin.com; lastvisited=index.html

This means that the document contains 3 Cookies: name, email and lastvisited, whose values ​​are kevin, kevin@kevin.com and index.html respectively. As you can see, the two Cookies are separated by semicolons and spaces, so we can use the cookieString.split('; ') method to get an array of each Cookie (first use var cookieString = document.cookie) .
The way to set a Cookie is to assign a value to document.cookie. Unlike assignment in other cases, assigning a value to document.cookie will not delete the original Cookies, but will only add Cookies or change the original Cookie. The format of the assignment:

document.cookie = 'cookieName=' escape('cookieValue')
';expires=' expirationDateObj.toGMTString();

Are you dizzy after seeing this? Woolen cloth? The above words that are not in bold should be copied exactly, and the words in bold should be changed according to the actual situation. cookieName represents the name of the Cookie, cookieValue represents the value of the Cookie, and expirationDateObj represents the date object name that stores the expiration date. If the expiration date does not need to be specified, the second line is not needed. If the expiration date is not specified, the browser defaults to expiration after closing the browser (that is, closing all windows).
Did you see some underlines above? These are the things that should be paid attention to.
First of all, escape() method: why must it be used? Because the requirement for Cookie value is "can only use characters that can be used in URL encoding".We know that the "escape()" method encodes the string according to the URL encoding method, then we only need to use an "escape()" method to process the value output to Cookie, and use "unescape()" to process the value output from Cookie The value received is foolproof. And the most common use of these two methods is to deal with Cookies. In fact, setting a Cookie is as simple as "document.cookie = 'cookieName=cookieValue'", but in order to avoid characters that are not allowed to appear in the URL in cookieValue, it is better to use escape().
Then the semicolon before “expires”: Just notice it. It's the semicolon and nothing else.
Finally toGMTString() method: The expiration date of the cookie is set in GMT format. Time in other formats has no effect.
Now let’s do some actual combat. Set a cookie with "name=rose" to expire in 3 months.


var expires = new Date();
expires.setTime(expires.getTime() 3 * 30 * 24 * 60 * 60 * 1000);
/* Three months x A month is treated as 30 days x A day is 24 hours
x One hour is 60 minutes x One minute is 60 seconds );

Why is the escape() method not used? This is because we know that rose is a valid URL-encoded string, that is, 'rose' == escape('rose'). Generally speaking, if you don't use escape() when setting a cookie, you don't need to use unescape() when getting a cookie.

Let’s do it again: write a function to find the value of a specified Cookie.

function getCookie(cookieName) {
var cookieString = document.cookie;
var start = cookieString.indexOf(cookieName '=');
// The reason for adding the equal sign is Avoid having
// the same string as cookieName in some Cookie values.
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 Here are some methods of string objects. If you don’t remember them (are you so forgetful?), please check them out quickly. All if statements in this function do not include else. This is because if the condition is true, the program will run return statements. If return is encountered in the function, the operation will be terminated, so it is okay not to add else. When this function finds Cookie, it will return the value of Cookie, otherwise it will 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() ;

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn