Home > Article > Web Front-end > Detailed introduction to the use of document.cookie in Javascript
This article mainly introduces the use of document.cookie in Javascript, and the function of remembering passwords and saving passwords through cookies. Friends in need can refer to the following
Set cookie
Each cookie is a name/value pair. You can assign the following string to document.cookie:
document.cookie="userId=828";
If you want to store multiple name/value pairs at one time, you can use semicolons and spaces (;) to separate them, for example:
document.cookie="userId=828; userName=hulk";
You cannot use semicolons (;) or commas (, ), equal sign (=) and space.
It's easy to do this in the name of the cookie, but the value to be saved is undefined. How to store these values?
The method is to use escape()function for encoding. It can express some special symbols in hexadecimal. For example, spaces will be encoded as "20%", which can be stored in cookie value, and using this solution can also avoid the occurrence of Chinese garbled characters. For example:
document.cookie="str="+escape("I love ajax");
is equivalent to: document.cookie="str=I%20love%20ajax";
When using escape() encoding, you need to use unescape() after extracting the value. Only by decoding can you get the original cookie value, which has been introduced before. Although document.cookie looks like a property and can be assigned different values. But it is different from general attributes. Changing its assignment does not mean losing the original value. For example, executing the following two statements continuously:
document.cookie="userId=828"; document.cookie="userName=hulk";
At this time, the browser will maintain two cookies, namely 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, just re- Assign a value, for example:
document.cookie="userId=929";
This will set the cookie value named userId to 929.
Get the value of the cookie
The following describes how to get the value of the cookie. The value of the cookie can be obtained directly from document.cookie:
var strCookie=document.cookie;
This will obtain a string consisting of multiple name/value pairs separated by semicolons. These name/value pairs include the names under the domain name. All cookies. For example:
It can be seen that all cookie values can only be obtained at one time, but the cookie name cannot be specified to obtain the specified value. This is the most troublesome part of processing cookie values.
Users must analyze this string themselves to obtain the specified cookie value. For example, to obtain the value of userId, this can be achieved:
In this way, the value of a single cookie is obtained
Using a similar method, you can get the value of one or more cookies. The main technique is still the related operations of strings and arrays.
Set the expiration date for cookies. Up to now, all cookies have been single-session cookies, that is, these cookies will be lost after the browser is closed. In fact, these cookies are only stored in memory without establishing a corresponding hard disk files.
In actual development, cookies often need to be saved for a long time, such as saving the user's login status. This can be achieved using the following options:
document.cookie="userId=828; expires=GMT_String";
where GMT_String is a time string expressed in GMT format. This statement sets the userId cookie to the expiration time represented by GMT_String. After this time, the cookie will Disappeared and inaccessible. For example:
If you want to set a cookie to expire after 10 days, you can do it like this:
<script language="JavaScript" type="text/javascript"> <!-- //获取当前时间 var date=new Date(); var expireDays=10; //将date设置为10天以后的时间 date.setTime(date.getTime()+expireDays*24*3600*1000); //将userId和userName两个cookie设置为10天后过期 document.cookie="userId=828; userName=hulk; expire="+date.toGMTString(); //--> </script>
Delete cookie
For To delete a cookie, you can set its expiration time to a past time, for example:
<script language="JavaScript" type="text/javascript"> <!-- //获取当前时间 var date=new Date(); //将date设置为过去的时间 date.setTime(date.getTime()-10000); //将userId这个cookie删除 document.cookie="userId=828; expire="+date.toGMTString(); //--> </script>
Specify the path to access the cookie. By default, if a cookie is created on a page, the page is Other pages in the directory can also access
this cookie. If there are subdirectories under this directory, you can also access it in the subdirectories.
In order to control the directory that cookies can access, you need to use the path parameter to set cookies. The syntax is as follows:
document.cookie="name=value; path=cookieDir";
where cookieDir represents the directory where 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 cookies available throughout the website, you can specify cookie_dir as the root directory, for example:
document.cookie="userId=320; path=/";
Specify the host name and path that can access the cookie. The host name refers to the same domain. Different hosts, for example: www.google.com and gmail.google.com are two different host names. By default, cookies created in one host cannot be accessed in another host, but they can be controlled through the domain parameter. The syntax format is:
document.cookie="name=value; domain=cookieDomain";
Take Google as an example, To achieve cross-host access, you can write it as:
document.cookie="name=value; domain=.google.com";
In this way, all hosts under google.com can access the cookie.
Comprehensive example: Constructing a general cookie processing function The cookie processing process is relatively complex and has certain similarities. Therefore, several functions can be defined to complete the common
operations of cookies, thereby achieving code reuse. Commonly used cookie operations and their function implementations are listed below.
1.添加一个cookie:addCookie(name,value,expireHours) 该函数接收3个参数:cookie名称,cookie值,以及在多少小时后过期。
这里约定expireHours为0时不设定过期时间,即当浏览器关闭时cookie自动消失。该函数实现如下:
<script language="JavaScript" type="text/javascript"> <!-- function addCookie(name,value,expireHours){ var cookieString=name+"="+escape(value); //判断是否设置过期时间 if(expireHours>0){ var date=new Date(); date.setTime(date.getTime+expireHours*3600*1000); cookieString=cookieString+"; expire="+date.toGMTString(); } document.cookie=cookieString; } //--> </script>
2.获取指定名称的cookie值:getCookie(name)
该函数返回名称为name的cookie值,如果不存在则返回空,其实现如下:
<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.删除指定名称的cookie:deleteCookie(name)
该函数可以删除指定名称的cookie,其实现如下:
<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>
The above is the detailed content of Detailed introduction to the use of document.cookie in Javascript. For more information, please follow other related articles on the PHP Chinese website!