Example of cookie read/write operations in js _ javascript tips-js tutorial

Source: Internet
Author: User
A cookie has a validity period. The default validity period of a cookie is from when the cookie is generated to when the browser is disabled. You can also set the cookie validity period to specify the expiration date; users can also disable or manually delete cookies. A cookie is a small segment of information stored on a computer hard disk with key/value pairs. The cookie storage capacity is approximately 4 kb, different browser manufacturers have slight differences in cookie size restrictions. The main essence of cookies is "recognition", which is used to do some things; cookies cannot get any other data from your hard disk, send computer viruses or get your email address. A cookie has a validity period. The default validity period of a cookie is from when the cookie is generated to when the browser is disabled. You can also set the cookie validity period to specify the expiration date; users can also disable or manually delete cookies.

Cookie is a string and a text string in a specific format

Format: cookieName = cookieValue; expires = expiresDate; path = URLpath; domain = siteDomain // cookie name, expiration date, stored URL, stored domain value;

Cookie Creation Method

To set cookies, we generally encapsulate them into a function:

The Code is as follows:


Function addCookie (sName, sValue, day ){
Var expireDate = new Date ();
ExpireDate. setDate (expireDate. getDate () + day );;
// Set the expiration time
Document. cookie = escape (sName) + '=' + escape (sValue) + '; expires =' + expireDate. toGMTString (); 6 // escape () converts Chinese characters to unicode encoding, and toGMTString () converts a date object to a string
}


Read cookie

After adding a cookie, how can we get it? It is very simple:

The Code is as follows:


Function getCookies (){
Var showAllCookie = '';
If (! Document. cookie = ''){
Var arrCookie = document. cookie. split (';');
// Use spilt (';') to cut all cookies and save them in the array arrCookie
Var arrLength = arrCookie. length;
For (var I = 0; ishowAllCookie + = 'C _ name: '+ unescape (arrCookie [I]. split ('=') [0]) + 'C _ value: '+ unescape (arrCookie [I]. split ('=') [1]) +'
'9}
Return showAllCookie;
}
}


The cookie can be automatically deleted if it has a validity period. You can also set its expiration date to delete it immediately.

It's just as simple. Continue:

The Code is as follows:


Function removeCookie (){
If (document. cookie! = ''& Confirm ('do you want to clear all cookies? ')){
Var arrCookie = document. cookie. split (';');
Var arrLength = arrCookie. length;
Var expireDate = new Date ();
ExpireDate. setDate (expireDate. getDate ()-1 );
For (var I = 0; ivar str = arrCookie [I]. split ('=') [0];
Document. cookie = str + '=' + '; expires =' + expireDate. toGMTString ();
}
}
}


We already know how to create, retrieve, and delete cookies. Now we need to use cookies.

Next we will use cookies to make a simple Timer:

The Code is as follows:


Var cookieCount = {};
CookieCount. count = function (){
Var count = parseInt (this. getCount ('mycount '));
Count ++;
Document. cookie = 'mycount = '+ count + '';
Alert ('sub' + count + 'access ');
}
CookieCount. setCount = function (){
// Create a cookie named myCount
Var expireDate = new Date ();
ExpireDate. setDate (expireDate. getDate () + 1 );
Document. cookie = 'mycount = '+ '0' +'; expires = '+ expireDate. toGMTString ();
}
CookieCount. getCount = function (countName ){
// Obtain the cookie name and Add 1 to it
Var arrCookie = document. cookie. split (';');
Var arrLength = arrCookie. length;
Var ini = true;
For (var I = 0; iif (countName = arrCookie [I]. split ('=') [0]) {
Return parseInt (arrCookie [I]. split ('=') [1]);
Break;
} Else {
Ini = false;
}
}
If (ini = false) this. setCount ();
Return 0;
}
CookieCount. count ();


Cookie Path

At the beginning of this article, we mentioned setting the cookie path: path = URL;

If the cookie is created in the subdirectory of the domain name, the cookie cannot be accessed by the domain name and other directories of the same level or higher level, the advantage of setting the path is that the sub-directories of the domain name and the domain name can be accessed as follows:

Document. cookie = 'cookiename = cookieValue; expires = expireDate; path = /'.

Cookie domain

Set domain: domain = siteDomain

This is mainly used to share a cookie in the same domain. For example, "www.taobao.com" and "ued.taobao.com" share a domain name "taobao.com ", if we want to allow the cookie under "www.taobao.com" to be accessed by "ued.taobao.com", we need to set the path attribute to "/" and set the cookie domain --> document. cookie = 'cookiename = cookieValue; expires = expireDate; path =/; domain = taobao.com '.

With the development of web, HTML5 provides two properties windows. sessionStorage and window. localStorage, and carries setItem, getItem, removeItem, clear and other methods, making the local data storage method easier and more convenient.
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.