The basic usage of cookies in JavaScript

Cookie object in JavaScript

Cookies are used to store user information on web pages.
What is a cookie?
Cookies are some data stored in a text file on your computer.
When the web server sends a web page to the browser, the server will not record user information after the connection is closed.
The purpose of cookies is to solve "how to record client user information":
  • When a user visits a web page, his name can be recorded in a cookie.
  • The next time the user visits the page, the user's access record can be read in the cookie.

Use JavaScript to create cookies
JavaScript can use the  document.cookie  property to create, read, and delete cookies.
In JavaScript, creating cookies looks like this:
document.cookie="username=John Doe";
You can also add an expiration time (in UTC or GMT time) to the cookie. 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 cookie path. By default, cookies belong to the current page.
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/";

Use JavaScript to read cookies
In JavaScript, the following code can be used to read cookies:
var x = document.cookie;
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=/";
The old cookie will be overwritten.
Use JavaScript to delete cookies
Deleting cookies is very simple. 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 n’t have to specify the cookie value when you delete.

code show as below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</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 οnlοad="checkCookie()"></body>	
</html>


Published 26 original articles · praised 0 · visits 9934

Guess you like

Origin blog.csdn.net/weixin_38246518/article/details/78768799