Cookie Overview
In the previous section, you used an immutable framework to store shopping bar data, and the product display page was constantly changing, although it was not rigorous to achieve a global variable. For example, if you right-click within the Navigation frames page and click Refresh on the shortcut menu, all JavaScript variables will be lost. Therefore, to implement a strict cross page global variable, this approach is not possible, another mechanism in javascript: cookies, you can achieve the requirements of a true global variable.
A cookie is a mechanism provided by the browser that provides the cookie properties of the document object to JavaScript. It can be controlled by JavaScript, not by the nature of JavaScript itself. A cookie is a file that is stored on a user's hard disk, which usually corresponds to a domain name, which is available when the browser accesses the domain name again. As a result, cookies can span multiple pages under one domain name, but cannot be used across multiple domain names.
Different browsers implement cookies differently, but their properties are the same. For example, in Windows 2000 and Windows XP, cookie files are stored in the Documents and Settings\username\cookie\ folder. The usual naming format is: UserName@domain.txt.
The cookie mechanism stores information on the user's hard disk, so it can be used as a global variable, which is one of its greatest advantages. It can be used in several situations.
(1) Save the user login status. For example, a user ID is stored in a cookie so that the next time a user accesses the page, there is no need to log on again, and many forums and communities now offer such functionality. Cookies can also set the expiration time, and the cookie will automatically disappear when the time limit is exceeded. As a result, the system can often prompt the user to remain logged in: The common options are one months, three months, a year, and so on.
(2) Tracking user behavior. For example, a weather forecast site that can display local weather conditions according to the user's chosen area. If you need to choose the location every time is cumbersome, when the use of cookies will appear very user-friendly, the system can remember the last visit to the region, the next time you open the page, it will automatically show the last user area of the weather. Because everything is done in the background, such a page is as easy to use as it is customized for a particular user.
(3) custom page. If the site provides the ability to change the skin or replace the layout, you can use cookies to record the user's options, such as background color, resolution, and so on. You can still save the interface style of the last visit when the user accesses the next time.
(4) Create a shopping cart. Just as in the previous example, a cookie is used to record the goods the user needs to buy, which can be submitted uniformly at checkout time. Taobao, for example, uses cookies to record the goods that users have viewed, making it easier to compare them at any time.
Of course, the above application is only part of the application that cookies can do, and more functions require global variables. The disadvantages of cookies are mainly focused on security and privacy protection. Mainly includes the following kinds:
(1) Cookies may be disabled. When a user attaches great importance to personal privacy protection, he is likely to disable the browser's cookie function;
(2) Cookies are browser-related. This means that even if you are accessing the same page, cookies stored between different browsers are not accessible to each other;
(3) Cookies may be deleted. Because each cookie is a file on the hard disk, it is likely to be deleted by the user;
(4) The cookie security is not high enough. All cookies are recorded as plain text in the file, so it is best to encrypt the information in advance if you want to save the username password.
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 semicolons (;), commas (,), Equals (=), and spaces in the name or value of a cookie. It is easy to do this in the name of a cookie, but the value to be saved is indeterminate. How do you store these values? The method is encoded with the escape () function, which can be used to represent some special symbols in hexadecimal notation, such as "20%", which can be stored in cookie values, and can be used to avoid the appearance of garbled Chinese. For example:
Copy Code code as follows:
Document.cookie= "str=" +escape ("I love Ajax");
Equivalent:
Copy Code code as follows:
Document.cookie= "Str=i%20love%20ajax";
When you use Escape () encoding, you need to use unescape () to decode after the value is fetched to get the original cookie value, as described earlier in this article.
Although Document.cookie looks like an attribute, it can be assigned a different value. However, unlike the general properties, changing its assignment does not mean losing the original value, such as executing the following two statements consecutively:
Copy Code code as follows:
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
The browser will maintain two cookies, respectively UserID and username, so give the document.cookie a value like executing a statement similar to this:
Copy Code code as follows:
Document.addcookie ("userid=828");
Document.addcookie ("Username=hulk");
In fact, the browser is the way to set cookies, if you want to change the value of a cookie, you just have to reassign the value, for example:
Document.cookie= "userid=929";
This sets the cookie value named UserID to 929.
Get the value of a cookie
The following describes how to get the value of a cookie. The value of a cookie can be obtained directly by Document.cookie:
var Strcookie=document.cookie;
This will get a string of multiple name/value pairs separated by semicolons that include all cookies under that domain name. For example:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
var Strcookie=document.cookie;
alert (Strcookie);
-->
</script>
From the output, it is only possible to get all the cookie values at once, not to specify the cookie name to get the specified value, which is the most troublesome part of handling the cookie value. The user must parse this string himself to get the specified cookie value, for example, to get the value of the UserID, which can be achieved by:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Set two cookies
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
Get cookie String
var Strcookie=document.cookie;
Cut multiple cookies to multiple name/value pairs
var arrcookie=strcookie.split (";");
var userId;
Iterate through the cookie array, processing each cookie on the
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>
This gets the value of a single cookie.
In a similar way, you can get the value of one or more cookies, and the main trick is still the related operations of strings and arrays.
set expiration date for cookie
Until now, all cookies are a single session cookie, that is, the cookies will be lost after the browser is closed, in fact these cookies are only stored in memory, but not the corresponding hard disk files.
In actual development, cookies often need to be saved for long periods of time, such as saving the user's login status. This can be accomplished with the following options:
Document.cookie= "userid=828; Expiress=gmt_string ";
Where Gmt_string is a time string in GMT format, this statement is to set the UserID cookie to the expiration time that gmt_string represents, over which the cookie disappears and is inaccessible. For example, if you want to set the cookie to expire after 10 days, you can do this:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Get current time
var date=new date ();
var expiresdays=10;
Set date to 10 days later
Date.settime (Date.gettime () +expiresdays*24*3600*1000);
Set the UserID and username two cookies to expire after 10 days
Document.cookie= "userid=828; Username=hulk; Expires= "+date.togmtstring ();
-->
</script>
Delete Cookies
To delete a cookie, you can set its expiration time to a past time, for example:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Get current time
var date=new date ();
Set Date to past time
Date.settime (Date.gettime ()-10000);
Remove UserID This cookie
Document.cookie= "userid=828; Expires= "+date.togmtstring ();
-->
</script>
specify the path to the cookie that can be accessed
By default, if a cookie is created on a page, other pages in the same directory as the page can also access the cookie. If there are subdirectories under this directory, they can also be accessed in subdirectories. For example, cookies created in 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 a cookie can access, you need to set the cookie using the path parameter, which is the following syntax:
Document.cookie= "Name=value; Path=cookiedir ";
Where Cookiedir represents a directory that can access cookies. For example:
Document.cookie= "userid=320; Path=/shop ";
means that the current cookie can only be used in the shop directory.
If you want the cookie to be available throughout the Web site, you can designate Cookie_dir as the root directory, for example:
Copy Code code as follows:
Document.cookie= "userid=320; path=/";
Specifies the host name that can access the cookie
Like a path, a host name refers to a different host 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 by the domain parameter in the form of the following syntax:
Document.cookie= "Name=value; Domain=cookiedomain ";
Take Google, for example, to achieve cross host access, which can be written as:
Document.cookie= "name=value;domain=.google.com";
In this way, the cookie is accessible to all hosts under Google.com.
Comprehensive example: Constructing a generic cookie handler function
The processing of cookies is more complex and has a certain similarity. Therefore, several functions can be defined to complete the general operation of the cookie, thus enabling the reuse of the code. The common cookie actions and their function implementations are listed below.
1. Add a Cookie:addcookie (name,value,expireshours)
The function receives 3 parameters: The cookie name, the cookie value, and how many hours after the expiration. This Convention does not set the expiration time when the expireshours is 0, that is, the cookie disappears automatically when the browser closes. This function is implemented as follows:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
<!--
function Addcookie (name,value,expireshours) {
var cookiestring=name+ "=" +escape (value);
Determine whether to set an expiration time
if (expireshours>0) {
var date=new date ();
Date.settime (date.gettime+expireshours*3600*1000);
Cookiestring=cookiestring+ "; Expires= "+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 and, if it does not exist, returns NULL, which is implemented as follows:
Copy Code code as follows:
<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 "";
}
-->
</script>
3. Deletes the Cookie:deletecookie (name) of the specified name
The function can delete a cookie with the specified name, which is implemented as follows:
Copy Code code as follows:
<script language= "JavaScript" type= "Text/javascript" >
<!--
function Deletecookie (name) {
var date=new date ();
Date.settime (Date.gettime ()-10000);
Document.cookie=name+ "=V; Expires= "+date.togmtstring ();
}
-->
</script>