JavaScript cookie Settings Get delete detailed _javascript tips

Source: Internet
Author: User
Tags setcookie
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 (;) To separate, 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 the cookie value, and the use of this scheme to avoid the appearance of garbled Chinese. 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 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:
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:
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:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Document.cookie= "userid=828";
Document.cookie= "Username=hulk";
var Strcookie=document.cookie;
alert (Strcookie);
-->
</script>

Figure 7.1 shows the cookie value for the output. This shows that you can only get all the cookie values at once, not 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:
<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>

So you get 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; Expires=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 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

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; Expire= "+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:

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,expirehours)

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 expirehours 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,expirehours) {
var cookiestring=name+ "=" +escape (value);
Determine whether to set an expiration time
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 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. Delete 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 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>

It can also be circulated on a different web:
Copy Code code as follows:

<script language= "JavaScript" type= "Text/javascript" >

function Setcookie (name,value)//two parameters, one is the name of the cookie, one is the value
{
var days = 30;//This cookie will be saved 30 day
var exp = n EW Date (); New Date ("December 31, 9998");
Exp.settime (Exp.gettime () + days*24*60*60*1000);
Document.cookie = name + "=" + Escape (value) + "; expires=" + exp.togmtstring ();
}
Function GetCookie (name)//Fetch cookies functions
{
var arr = document.cookie.match (New RegExp ("(^|)" +name+ "= ([^;] *)(;|$)"));
if (arr!= null) return unescape (arr[2);

}
Function Delcookie (name)/delete cookie
{
var exp = new Date ();
Exp.settime (Exp.gettime ()-1);
var cval=getcookie (name);
if (cval!=null) document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();
}

Setcookie ("Xiaoqi", "3")
Alert (GetCookie (' Xiaoqi '));
</script>
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.