Home >Web Front-end >JS Tutorial >How to implement cookie operation in javascript
Method: 1. Use the "document.cookie="name=value;"" statement to set the cookie or modify the cookie value; 2. Use the "document.cookie" statement to obtain the cookie value; 3. Pass the valid The time "expires" is set to the expiration value to delete the cookie.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Cookies are variables stored on a visitor's computer. When a user visits a website, data can be stored on the visitor's computer through cookies. Later, when the user requests the page again through the browser on the same computer, this cookie is sent and the cookie can be used to identify the user.
1. Setting cookies
Using cookies to store data is achieved by setting cookies. Each cookie is a name/value pair. The name/value pairs are connected with an equal sign, and the name/value pair is assigned to document.cookie. Multiple name/value pairs can be assigned to document.cookie at one time, using semicolons and spaces to separate each name/value pair.
The basic format of setting cookies is as follows:
document.cookie = "名称1=值1[; 名称2=值2; …]";
The example of setting cookies is as follows:
document.cookie = "username=abc"; document.cookie = "age=23"; document.cookie = "username=abc; age=23";
It should be noted that semicolons cannot be used in the name or value of cookies; and equal sign = equal sign. If you want to store these symbols, you need to use the escape() function for encoding. For example: document.cookie="str=" escape("username=nch"), this code is equivalent to: document.cookie="str=username=nch", that is, the equal sign is encoded as =. When using escape() encoding, you need to use unescape() to decode after taking out the value to get the original cookie value.
In addition, when the value in the cookie set using the above format is stored in the user's computer, the data of different websites is distinguished in the form of website domain name, and different browsers store cookies in different locations, so different browsing Cookies stored between servers cannot be accessed by each other. In addition, there is a limit to the number of cookies stored under the same domain name, and different browsers have different limits on the number of cookies stored. Moreover, the size of the content stored in each cookie is also limited, and different browsers have different size limits.
2. Modify cookie value
If you want to change a cookie value, just reassign it, for example: document.cookie="age=36 ";
This way you can modify the cookie value of age=23 set previously.
3. Get cookie
When you get the cookie under the current website through document.cookie
, you get the value in the form of a string. This value contains all cookies under the current website. It will concatenate all cookies through a semicolon and a space.
To obtain different cookie values, you can use the split() method to convert the string containing semicolons and spaces into a string array separated by semicolons, and then traverse the string array. Each name/value pair can be obtained. Use the split() method again to convert this name/value pair into an array containing names and values separated by equal signs, and you can get the value of the specified cookie name.
For example, the code to get the value of cookie named age is as follows:
document.cookie = "username=abc; age=23"; var arr1 = document.cookie.split(';'); for(var i = 0; i < arr1.length; i++){ var arr2 = arr1[i].split('='); if(arr2[0] == 'age'){ alert(arr2[1]); } }
4. Set the validity time of cookie
By default, cookie It is temporarily stored, that is, it is stored in memory by default and is not stored on the hard disk, so the stored cookie will be automatically destroyed after the browser process is closed. If you want to save cookies in your computer for a period of time or permanently, you need to set a valid time when setting the cookie. The setting format is as follows:
document.cookie = "名称=值;expires="+字符串格式的时间;
For example:
var oDate = new Date(); oDate.setDate(oDate.getDate()+10);//访问页面后的10天过期 //设置cookie的有效时间,时间为字符串格式 document.cookie = 'username=abc;expires='+oDate.toGMTString();
5. Delete the cookie
and directly set the validity time of the cookie to a certain time in the past. For example:
var oDate = new Date(); oDate.setDate(oDate.getDate()-1);//访问页面的前一天 document.cookie = 'username=abc;expires='+oDate.toGMTString();
[Example 1] Use document to operate cookies.
<!doctype html> <html> <head> <meta charset="utf-8"> <title>使用cookie记住登录用户名</title> <script> window.onload = function(){ var oUsername = document.getElementById('username'); var oLogin = document.getElementById('login'); var oDel = document.getElementById('del'); //判断用户是否曾经登录过 if(getCookie('username')){ oUsername.value = getCookie('username'); } //定义一个函数来获取指定名称的cookie值: function getCookie(key){ var arr1 = document.cookie.split(';'); for(var i = 0; i < arr1.length; i++){ var arr2 = arr1[i].split('='); if(arr2[0] == key){ return unescape(arr2[1]);//对编码后的内容进行解码 } } } //定义一个函数来设置cookie,同时设置cookie的有效时间 function setCookie(key,value,t){ var oDate = new Date(); oDate.setDate(oDate.getDate()+t); //使用escape()对内容进行编码 document.cookie = key+'='+escape(value)+';expires='+oDate.toGMTString(); } //定义一个函数移除cookie function removeCookie(key){ setCookie(key,'',-1); } oLogin.onclick = function(){ alert('登录成功'); //将输入的用户名存储在cookie中,且在登录5天后cookie过期 setCookie('username',oUsername.value,5); } oDel.onclick = function(){ removeCookie('username'); oUsername.value = '';//移除cookie后清空文本框内容 } }; </script> </head> <body> <input type="text" id="username"/> <input type="button" value="登录" id="login"/> <input type="button" value="删除用户名cookie" id="del"/> </body> </html>
Note: Firefox and IE only allow temporary operation of cookies locally, and cookies cannot be obtained after closing the browser. Chrome, on the other hand, does not allow local manipulation of cookies. When Example 1 is published to a Web server and then accessed, these browsers can manipulate cookies.
The following figure shows the results of accessing and publishing to the Tomcat Web server in the Chrome browser and clicking the login button and delete button after entering the user name (the Tomcat server is on this machine, so you can use localhost as the domain name to access it).
Enter the username and click the login button. Close the Chrome browser before clicking the delete username cookie button. process, and then open Chrome again to access Example 1, you can get the result shown in Figure 3, that is, the user name will be automatically displayed in the text box. If you click the delete username cookie button, close the Chrome browser process, and then open Chrome again to access Example 1, you will get the result shown in Figure 4. At this time, the username stored in the cookie has been deleted and cannot be displayed. text box.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to implement cookie operation in javascript. For more information, please follow other related articles on the PHP Chinese website!