The setting of the JavaScript cookie gets the deletion details

  • 2020-03-30 01:40:20
  • OfStack

Set the cookie

Each cookie is a name/value pair. You can assign the following string to document.cookie:
Document. The cookie = "userId = 828";

If you want to store more than one name/value pair at a time, you can use a semicolon with a space (; ), for example:
Document. The cookie = "userId = 828; The userName = hulk ";

You cannot use a semicolon (;) in the name or value of a cookie. , comma (,), equal sign (=), and space. This is easy to do in the name of the cookie, but the value to be saved is uncertain. How do you store these values? The method is encoded with the escape() function, which USES hexadecimal notation for special symbols, such as Spaces that are encoded as "20%" to store in cookie values. Such as:
Document. The cookie = "STR =" + escape (" I love ajax ");

Is equivalent to:
Document. The cookie = "STR = % 20 I love % 20 ajax";

When the escape() encoding is used, unescape() is used to decode the extracted value to get the original cookie value, as described earlier.

Although document.cookie looks like a property, it can be assigned different values. But unlike a normal property, changing its assignment does not mean losing the original value, such as executing the following two statements consecutively:
Document. The cookie = "userId = 828";

Document. The cookie = "userName = hulk";

The browser will maintain two cookies, userId and userName, so assigning a value to document.cookie is more like executing a statement like this:
Document. Addcookie (" userId = 828 ");

Document. Addcookie (" userName = hulk ");

In fact, the browser sets the cookie in this way. If you want to change the value of a cookie, you just need to re-assign it, for example:
Document. The cookie = "userId = 929";

This sets the value of the cookie with the name userId to 929.

Gets the value of the cookie

Here's how to get the value of a cookie. The value of cookie can be directly obtained by document.cookie:
Var strcookie = document. Cookies;

This gets a string of name/value pairs separated by semicolons that contain all cookies under the domain name. Such as:
< Script language = "JavaScript" type = "text/JavaScript" >
< ! --
Document. The cookie = "userId = 828";
Document. The cookie = "userName = hulk";
Var strcookie = document. Cookies;
Alert (strcookie);
/ / - >
< / script>

Figure 7.1 shows the output cookie value. As you can see, getting all the cookie values at once, rather than specifying the cookie name to get the specified value, is the most difficult part of dealing with cookie values. The user must analyze the string to get the specified cookie value. For example, to get the value of the userId, you can:
< Script language = "JavaScript" type = "text/JavaScript" >
< ! --
// sets two cookies
Document. The cookie = "userId = 828";
Document. The cookie = "userName = hulk";
// gets the cookie string
Var strcookie = document. Cookies;
// cut multiple cookies into multiple name/value pairs
Var arrcookie = strcookie. Split ("; ");
Var userId.
// traverses the cookie array, processing each cookie pair
For (var I = 0; I< Arrcookie. Length; I++) {
Var arr = arrcookie [I]. The split (" = ");
// finds the cookie with the name userId and returns its value
If (" userId "= = arr [0]) {
UserId = arr [1];
Break;
}
}
Alert (userId);
/ / - >
< / script>

This gives you 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 string and array related operations.

Set an end date for the cookie

Until now, all cookies are single-session cookies, which means that they will be lost after the browser is closed. In fact, these cookies are only stored in memory, and no corresponding hard disk file is created.

In actual development, cookies often need to be kept for a long time, such as to save the status of user login. This can be done with the following options:

Document. The cookie = "userId = 828; Expires = GMT_String ";

Where GMT_String is a time string in the format of GMT, this statement is to set the cookie userId as the expiration time of GMT_String, after which the cookie will disappear and be inaccessible. For example, if you want to set the cookie to expire in 10 days, you can do this:
 
<script language="JavaScript" type="text/JavaScript"> 
<!-- 
//Get the current time
var date=new Date(); 
var expireDays=10; 
//Set the date to 10 days from now
date.setTime(date.getTime()+expireDays*24*3600*1000); 
//Set the userId and userName cookies to expire in 10 days
document.cookie="userId=828; userName=hulk; expire="+date.toGMTString(); 
//--> 
</script> 

Delete the cookie

To delete a cookie, set its expiration time to a past time, for example:
 
<script language="JavaScript" type="text/JavaScript"> 
<!-- 
//Get the current time
var date=new Date(); 
//Set the date to the past time
date.setTime(date.getTime()-10000); 
//Delete the cookie userId
document.cookie="userId=828; expire="+date.toGMTString(); 
//--> 
</script> 

Specifies a path to the cookie

By default, if a cookie is created on a page, it can be accessed by other pages in the directory where the page resides. If there are subdirectories in this directory, you can also access them in the subdirectory. For example, cookies created at www.xxxx.com/html/a.html can be accessed at www.xxxx.com/html/b.html or www.xxx.com/html/some/c.html, but not at www.xxxx.com/d.html.

To control the directory that cookie can access, you need to use the path parameter to set cookie. The syntax is as follows:
Document. The cookie = "name = value; Path = cookieDir ";

Where cookieDir represents the directory where cookies are accessible. Such as:
Document. The cookie = "userId = 320; Path = / shop ";

This means that the current cookie can only be used in the shop directory.

To make cookies available throughout the site, specify cookie_dir as the root directory, for example:

Document. The cookie = "userId = 320; Path = / ";

Specifies the hostname of the accessible cookie

Like paths, hostnames refer to different hosts in the same field, for example: www.google.com and gmail.google.com are two different hostnames. By default, cookies created in one host cannot be accessed under another host, but can be controlled by domain parameters. The syntax is:

Document. The cookie = "name = value; Domain = cookieDomain ";

Take Google as an example. To achieve cross-host access, write:

Document. The cookie = "name = value; Domain=.google.com ";

This way, all hosts under google.com can access the cookie.

Composite example: construct a generic cookie handler

The processing process of cookie is complex and has certain similarity. Therefore, several functions can be defined to complete the general operation of cookie, so as to achieve code reuse. Common cookie operations and their functional implementations are listed below.

1. Add a cookie: addcookie(name,value,expireHours)

This function takes three parameters: the name of the cookie, the value of the cookie, and how many hours later it expires. Here, expireHours is set to 0 without setting an expiration time, that is, the cookie will automatically disappear when the browser is closed. This function is implemented as follows:
 
<script language="JavaScript" type="text/JavaScript"> 
<!-- 
function addcookie(name,value,expireHours){ 
var cookieString=name+"="+escape(value); 
//Determines 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. Get the cookie value of the specified name: getcookie(name)

This function returns the cookie value with the name. If it does not exist, it returns null. Its implementation is 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. Deletecookie: deletecookie(name)

This function can delete the specified name of the cookie, its implementation is as follows:
The same code at the page code block index 3
You can also use another one that is circulating on the Internet:
 
<script language="JavaScript" type="text/JavaScript"> 

function SetCookie(name,value)//Two parameters, the name of the cookie and the value
{ 
var Days = 30; //This cookie will be stored for 30 days
var exp = new 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)//Take cookies function
{ 
var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); 
if(arr != null) return unescape(arr[2]); return null; 

} 
function delCookie(name)//Delete the 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 articles: