What are Cookies?
Cookies are pieces of data that are stored in text files on your computer.
When the web server sends a web page to the browser, the server will not record the user's information after the connection is closed.
The role of Cookies is to solve "how to record user information on the client side":
When a user visits a web page, his name can be recorded in the cookie.
The next time the user visits this page, the user access record can be read in the cookie.
Cookies are stored in the form of name/value pairs, as follows:
username=John Doe
When the browser requests a web page from the server , the cookies belonging to the page will be added to the request. The server obtains user information in this way.
Document cookie attribute definition
The cookie attribute can set or query all cookies related to the current document. The syntax is as follows:
document.cookie [ = name1=value1; expire=GMT_String; path=; domain=;]
Set cookie value
Now we need to set two cookies:
user_id=2;
user_name=admin;
JavaScript code As follows:
document.cookie = "user_id=2";
document.cookie = "user_name=admin";
Set cookie expiration time, path and scope
The following example sets the expiration time to one day, the path is the website root directory, and all cookies under this domain name are shared:
//Get the current time
var date=new Date();
date.setTime(date.getTime()+24*3600*1000);
document.cookie = "user_id=2;path=/;domain=.5idev.com;expire=" +date.toGMTString();
Setting cookies has special symbols
Semicolons (;) cannot be used in cookie names or values. , comma (,), equal sign (=) and spaces. When these symbols need to be retained in the value, the escape() function needs to be used for encoding. It can express some special symbols in hexadecimal.
document.cookie = "test="+escape("JavaScript cookie test");
After taking out the value, use unescape() to decode it to get the original cookie value. This This method can also effectively avoid Chinese garbled characters, etc.
Get the cookie value
You can directly get the cookie value of the current page through document.cookie, and the result is a string. The following example reads the cookie for the current page (if any):
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p>与本文档相关的 cookies(如果存在的话):</p> <script type="text/javascript"> document.write(document.cookie) </script> </body> </html>
Function to detect cookie value
Finally, we can create a function that detects whether a cookie has been created.
If cookies are set, a greeting message will be displayed.
If the cookie is not set, a pop-up window will be displayed to ask the visitor's name, and the setCookie function will be called to store the visitor's name for 365 days:
function checkCookie() { var username=getCookie("username"); if (username!="") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:",""); if (username!="" && username!=null) { setCookie("username",username,365); } } }
Use JavaScript to create cookies
JavaScript can use the document.cookie attribute to create, read, and delete cookies.
In JavaScript, create a cookie as follows:
document.cookie="username=John Doe";
You can also add An expiration time (in UTC or GMT time). By default, cookies are deleted when the browser is closed:
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT";
You can use the path parameter to tell the browser the path to the cookie. By default, the cookie belongs to the current page.
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
Read Cookies using JavaScript
In JavaScript, you can use the following code to read cookies:
var x = document.cookie;
Tip: document.cookie will return all cookies in the form of strings, type format: cookie1=value; cookie2=value; cookie3=value;
Use JavaScript to modify cookies
In JavaScript, modifying cookies is similar to creating cookies, as follows:
document.cookie= "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";
Old cookies will be overwritten.
Deleting Cookies using JavaScript
Deleting cookies is very easy. You only need to set the expires parameter to the previous time, as shown below, set to Thu, 01 Jan 1970 00:00:00 GMT:
document.cookie = "username=; expires= Thu, 01 Jan 1970 00:00:00 GMT";
Note that you do not have to specify a cookie value when you delete it.
Complete example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php.cn</title> </head> <head> <script> function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname){ var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i].trim(); if (c.indexOf(name)==0) return c.substring(name.length,c.length); } return ""; } function checkCookie(){ var user=getCookie("username"); if (user!=""){ alert("Welcome again " + user); } else { user = prompt("Please enter your name:",""); if (user!="" && user!=null){ setCookie("username",user,30); } } } </script> </head> <body onload="checkCookie()"></body> </html>