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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
