Understanding of Cookies

Source: Internet
Author: User

Set Cookies
Each cookie is a name/value pair, and you can assign a string such as the following to Document.cookie:
Document.cookie= "userid=828";
If you want to store more than one name/value pair at a time, you can use a semicolon plus a space (; ) separated, for example:
Document.cookie= "userid=828; Username=hulk ";
You cannot use a semicolon (;), a comma (,), an equal sign (=), and a space in the name or value of a cookie. Do it in the name of the cookie

It's easy to get to this point, but the value to save is indeterminate. How do you store these values? The method is encoded with the escape () function, which can use hexadecimal notation for some special symbols, such as spaces that will be encoded as "20%", which can be stored in

Cookie value, and the use of this scheme can also avoid the appearance of Chinese garbled. For example:
Document.cookie= "str=" +escape ("I love Ajax");
Equivalent:
Document.cookie= "Str=i%20love%20ajax";
When you use Escape () encoding, you need to use unescape () to decode the value after it is removed to get the original cookie value.

Although Document.cookie looks like a property, you can assign different values. However, unlike the general properties, changing its assignment does not mean losing the original value, such as executing the following two statements consecutively:
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
At this point the browser will maintain two cookies, namely UserID and username, so give document.cookie a value like executing a statement like this:
Document.addcookie ("userid=828");
Document.addcookie ("Username=hulk");
In fact, the browser is in this way to set the cookie, if you want to change the value of a cookie, simply re-assign the value, for example:
Document.cookie= "userid=929";
This sets the cookie value named UserID to 929.

get the value of a cookie
Here's how to get the value of a cookie. The value of a cookie can be obtained directly from Document.cookie:
var Strcookie=document.cookie;
This will get a string of multiple name/value pairs separated by semicolons that includes all cookies under that domain name

<script language= "JavaScript" type= "Text/javascript" >
<!--
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
var Strcookie=document.cookie;
alert (Strcookie);
-
</script>

Name to get the specified value, which is the most troublesome part of handling cookie values. The user must parse the string himself to get the specified cookie value, for example, to get the value of the UserID, this can be done:

<script language= "JavaScript" type= "Text/javascript" >
<!--
Set two cookies
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
Get cookie String
var Strcookie=document.cookie;
Cutting multi-Cookie into multiple name/value pairs
var arrcookie=strcookie.split (";");
var userId;
Iterate through the cookie array and process each cookie against
for (Var i=0;i<arrcookie.length;i++) {
var arr=arrcookie[i].split ("=");
Find the cookie with the name UserID and return its value
if ("UserId" ==arr[0]) {
USERID=ARR[1];
Break
}
}
alert (USERID);
-
</script>

In a similar way, you can get the value of one or more cookies, and the main technique is still related to string and array operations.

set end date for cookies
Until now, all cookies are single-session cookies, which will be lost when the browser is closed, in fact, these cookies are stored in memory only, and no corresponding hard disk files are created.
In real-world development, cookies often require long-term preservation, such as saving the user's login status. This can be accomplished with the following options:
Document.cookie= "userid=828; Expires=gmt_string ";
Where Gmt_string is a time string in GMT format, this statement is to set the UserID this cookie to

Gmt_string indicates that the expiration time, more than this time, the cookie will disappear and inaccessible. For example, if you want to add a cookie

Set to expire after 10 days, this can be done:

<script language= "JavaScript" type= "Text/javascript" >
<!--
Get current time
var date=new date ();
var expiredays=10;
Set date to 10 days later
Date.settime (Date.gettime () +expiredays*24*3600*1000);
Set the UserID and username two cookies to expire after 10 days
Document.cookie= "userid=828; Username=hulk; Expire= "+date.togmtstring ();
-
</script>


Delete Cookies
In order to delete a cookie, you can set its expiration time to a past time, for example:

<script language= "JavaScript" type= "Text/javascript" >
<!--
Get current time

var date=new date ();
Set date to the past time

Date.settime (Date.gettime ()-10000);
Delete the UserID cookie

Document.cookie= "userid=828; Expire= "+date.togmtstring ();
-
</script>

specify the path to an accessible cookie
By default, if a cookie is created on a page, the cookie is also accessible to other pages in the same directory as the page. If there are subdirectories under this directory, they can also be accessed in subdirectories. For example, in

Cookies created in the www.xxxx.com/html/a.html can be www.xxxx.com/html/b.html or

Www.xxx.com/html/some/c.html, but cannot be accessed by www.xxxx.com/d.html.
To control which directories the cookie can access, you need to use the path parameter to set the cookie with the following syntax:
Document.cookie= "Name=value; Path=cookiedir ";
Where Cookiedir represents the directory in which cookies can be accessed. For example:
Document.cookie= "userid=320; Path=/shop ";
means that the current cookie can only be used in the shop directory.
If you want to make a cookie available under the entire Web site, you can specify Cookie_dir as the root directory, for example:
Document.cookie= "userid=320; path=/";


Specify the host name of the accessible cookie
Similar to paths, host names refer to different hosts under the same domain, for example: www.google.com and gmail.google.com are two different host names. By default, a cookie created in one host cannot be accessed under another host, but it can be controlled through the domain parameter in the following syntax format:
Document.cookie= "Name=value; Domain=cookiedomain ";
Take Google, for example, to achieve cross-host access, can be written as:
Document.cookie= "name=value;domain=.google.com";
This allows the cookie to be accessed by all hosts under Google.com.


Composite example: Constructing a common cookie handler function
The process of cookie processing is more complicated and has some similarity. Therefore, several functions can be defined to complete the common use of cookies.

Operation, which enables the reuse of code. The following is a list of commonly used cookie operations and their function implementations.
1. Add a Cookie:addcookie (name,value,expirehours)
The function receives 3 parameters: The cookie name, the cookie value, and the number of hours after which it expires. There is no expiration time when the expirehours is 0, i.e. the cookie disappears automatically when the browser is closed. The function is implemented as follows:

<script language= "JavaScript" type= "Text/javascript" >
<!--
function Addcookie (name,value,expirehours) {
var cookiestring=name+ "=" +escape (value);
Determine if the expiration time is set


if (expirehours>0) {
var date=new date ();
Date.settime (date.gettime+expirehours*3600*1000);
Cookiestring=cookiestring+ "; Expire= "+date.togmtstring ();
}
document.cookie=cookiestring;
}
-
</script>

2. Gets the cookie value for the specified name: GetCookie (name)
The function returns a cookie value named name, or null if it does not exist, with the following implementation:

<script language= "JavaScript" type= "Text/javascript" >
<!--
function GetCookie (name) {
var Strcookie=document.cookie;
var arrcookie=strcookie.split (";");
for (Var i=0;i<arrcookie.length;i++) {
var arr=arrcookie[i].split ("=");
if (Arr[0]==name) return arr[1];
}
Return "";
}
-

function GetCookie (cookie_name) {
var results = Document.cookie.match (' (^|;)? ' + cookie_name + ' = ([^;] *) (; |$) ');

if (results)
Return (Unescape (results[2));
Else
return null;
}
</script>

3. Delete Cookie:deletecookie (name) of the specified name
The function can delete a cookie with the specified name, which is implemented as follows:

<script language= "JavaScript" type= "Text/javascript" >
<!--
function Deletecookie (name) {
var date=new date ();
Date.settime (Date.gettime ()-10000);
Document.cookie=name+ "=V; Expire= "+date.togmtstring ();
}
-
</script>

We already know that there is a cookie attribute in the Document object. But what is a Cookie? "Some Web sites store information on your hard disk with very small text files, which are called cookies. "--msie help. In general, cookies are CGI or similar, created with higher-level HTML files, programs, and so on, but JavaScript also provides full access to cookies.

We have to learn the basics of cookies first.

Every Cookie is like this: <cookie >=< value >

The limitations of the <cookie name > are much the same as the JavaScript naming restrictions, with fewer "Cannot use JavaScript keywords" and more "only characters that can be used in URL encoding". The latter is difficult to understand, but as long as you name only with letters and numbers, there is no problem at all. The < value > requirement is also "only use characters that can be used in URL encoding."

Each cookie has an expiration date, and once the computer's clock has expired, the cookie is 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 every site, has its own cookies, which can only be accessed by the Web pages under this site, and pages from other sites or unauthorized areas under the same site are inaccessible. Each "group" of cookies has a specified total size (approximately 2KB per "group"), one exceeds the maximum total size, then the first expired cookie is first deleted to allow the new cookie to "settle".

Now let's learn to use the Documents.cookie property.

If you use the Documents.cookie property directly, or, in some way, such as assigning a value to a variable, to get the value of Documents.cookie, we can know how many cookies, each cookie's name, and its value are in the current document. For example, add "document.write (Documents.cookie)" to a document and the results show:

Name=kevin; [email protected]; Lastvisited=index.html

This means that the document contains 3 Cookies:name, email and lastvisited, and their values are Kevin, [email protected] and index.html. As you can see, the two Cookies are separated by a semicolon and a space, so we can use Cookiestring.split ('; ') method to get an array separated by each Cookie (first with var cookiestring = Documents.cookie).

The way to set a Cookie is to assign a value to Documents.cookie. Unlike other assignments, assigning a value to Documents.cookie does not delete the original cookies, but only adds cookies or changes to the original cookie. Format of assignment:

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

Did you see the dizziness? CookieName represents the name of the cookie, Cookievalue represents the value of the cookie, Expirationdateobj represents the date object name that stores the expiration date, and if no expiration date is required, the second line is not required. Without specifying an expiration date, the browser defaults to expire after closing the browser (that is, closing all windows).

First Escape () method: Why must you use it? Because the value of the Cookie requires "only characters that can be used in URL encoding". We know that the "escape ()" method encodes the string as a URL encoding, so we only need to use an "escape ()" method to process the output to the cookie value, and "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 "Documents.cookie = ' cookiename=cookievalue '" is so simple, but in order to avoid appearing in the Cookievalue URL is not allowed to appear in the characters, or with an escape () good.
Then the semicolon in front of "expires": just notice. is a semicolon and not the other.
Last toGMTString () method: Setting the age of the Cookie is in GMT format, the time in other formats is not useful.

Now let's do the actual combat. Set a "Name=rose" Cookie that expires after 3 months.

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 one minute 60 seconds X one second 1000 milliseconds */
Documents.cookie = ' name=rose;expires= ' + expires.togmtstring ();

Why is the escape () method not used? This is because we know that Rose is a valid URL-encoded string, which means ' rose ' = = Escape (' Rose '). In general, if you do not use escape () when setting a cookie, you do not need to unescape () to get a cookie.

One more time: Write a function that looks for the value of the specified Cookie.

function GetCookie (cookiename) {
var cookiestring = Documents.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)//Cannot find
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 do not remember (you are not so memory AH), please go to check. All of the IF statements in this function are not with else, because if the condition is true, the program is running the return statement, and the return is encountered in the function, it will terminate the operation, so it is no problem to add else. When the function finds a cookie, it returns the value of the cookie, otherwise it returns "null".

Now we want to delete the Name=rose Cookie we just set.

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

As you can see, you just need to change the expiration date to one o'clock (this is 1 milliseconds earlier), and then set the cookie in the same way that you can erase the cookie.

Understanding of Cookies

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.