A few lines of code and a few lines of analysis teach you how to read cookies

Cookie

What are cookies?

A cookie is some data, stored in a text file on your computer.
When the web server sends a web page to the browser, the server does not record the user's information after the connection is closed. The function of the cookie is to solve "how to record the client's user information": when the user visits the web page, his name can be recorded in the cookie. When the user visits the page next time, the user visit record can be read in the cookie.
What is its function?
First of all, you need to know the HTTP protocol. The http protocol is a web page transfer protocol, a hypertext transfer protocol, and a stateless protocol, and cookies are a session tracking technology, which is used to record the status of http.
Where is it recorded?
Recorded in the browser's cache, there are some restrictions, as follows:
Size limit: 4K ±
Quantity limit: 50 ±
Time limit: By default, the browser is closed and the (session level)
read limit is cleared: Cross-domain is not allowed, (path, browse device)
how to record it?
This touches on the key points we want to talk about. Usage of cookies.


The core operation requires writing the value of the cookie in the value of the cookie
: the format of key and value: such as: name=val and
configuration information: the configuration information mainly includes the following two:
limited period: expires
path: path
configuration information and cookie Use ; to separate the information

Addition, deletion, modification and query of cookies

1. How to get cookies

document.cookie

2. Setting a cookie means setting a value for a cookie.

document.cookie = "asdasd"

3. Modify the cookie, that is, set a new value for the cookie, which is not so complicated

document.cookie = "user=adasda;path=/1911";

4. Delete cookie: Expiration time, active expiration , you can set the limited period to yesterday, so you don’t have to think about it every time.

		var d = new Date();
		d.setDate(d.getData()-1);
		document.cookie = "user=admin;expires="+d+";path=/";
		document.cookie = "cookie的信息,将有限期设置为昨天"

Encapsulation of cookies

The encapsulation of cookies is very useful, you need to keep in mind, (even if you don’t know how to write it yourself, you can summarize it and save it for emergencies)

		function setCookie(key,val,options){
    
    
			//1.设置options的默认值为对象
			options = options || {
    
    };
//			2.解析options身上的path属性
			var p = options.path ? ";path="+options.path : "";
//			3.解析options身上的expires属性
			var e = "";
			if(options.expires){
    
    
				var d = new Date();
				d.setDate(d.getDate()+options.expires);
				e = ";expires="+d;
			}
//			4.拼接字符,并设置coolie
			document.cookie = key+"="+ val + p + e;
		}
		//删除cookie的方法
		function removeCookie(key,options){
    
    
			options = options || {
    
    };
			var d = new Date();
			d.setDate(d.getDate()-1);
			
			//设置cookie相同的名字,值无所谓,有限期修改。
			setCookie(key,null,{
    
    
				expires:-1,
				path:options.path
			})	
		}

Get the cookie package

//获取cookie
		function getCookie(key){
    
    
			console.log(document.cookie.split("; "));
			var arr = document.cookie.split("; ");//注意空格
			for(var i =0;i<arr.length;i++){
    
    
				//console.log(arr[i].split("="));
				//console.log(arr[i].split("=")[0]);
				if(arr[i].split("=")[0] == key){
    
    
					return arr[i].split("=")[1];
				}	
			}
			return "";
		}
		console.log(getCookie("d"));

Even though many people understand the encapsulation of cookies , they may not be able to use them because they are not written by themselves, but they are just summaries. I will teach you a few simple usages, and you can draw inferences from one instance.

1. Set a cookie without an address

setCookie("hah","jquba");

2. Set a cookie with a limited period and address

		setCookie("user","admin",{
    
    
			expires:4,
			path:"/Myphp"
		});

3. Get cookies

getCookie("key")

4. Deleting cookies
can be deleted directly in the browser, or by calling the encapsulation function that deletes cookies

		removeCookie("key");
		//或,下面的是删除有地址的cookie
		removeCookie("user",{
    
    
			path:"/Myphp"
		})

Application of cookies, shopping cart

This is an example of a typical cookie application (it needs to be run on the server, either locally or online.)
list.html code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>购物车商品列表</title>
		<style>
	        #cont{
     
     width:1000px;overflow: hidden;border: solid 2px black;margin: 0 auto;}
	        .box{
     
     width:250px;border:solid 1px black;box-sizing: border-box;text-align: center;float: left;}
	        .box p{
     
     line-height:20px;height:40px;overflow: hidden;}
	        .box img{
     
     width:80%;height:200px;}
	        .box em{
     
     width:100px;height:40px;display: block;margin: 10px auto;background: cornflowerblue;color: #fff;text-align: center;line-height: 40px;border-radius: 6px;cursor: pointer;}
	    </style>
	</head>
	<body>
		<div id="cont">
	        <p>商品卖光了...</p>
	    </div>
	</body>
	<!--//开启之前引入-->
	<script src="../ajax.js"></script>
	<script src="../cookie/cookie.js"></script>
	<script type="text/javascript">
		class List{
     
     
			constructor(){
     
     
				this.url = "http://localhost/Myphp/shopping/data/goods.json";
				this.cont = document.getElementById("cont");
				
				this.load();
				this.addEvent();
			}
			load(){
     
     
				//开启ajax
				var that = this;
				ajaxGet(this.url,function(res){
     
     
					that.res = JSON.parse(res);
//					console.log(res);//一定先看数据。
					that.display();
				})
			}
			display(){
     
     
				//console.log(this.res);
				var str="";
				for(var i =0;i<this.res.length;i++){
     
     
					
					str += `
					<div class="box" index="${
       
       this.res[i].goodsId}">
					<img src=${
       
       this.res[i].img} alt="">
					<p>${
       
       this.res[i].name}</p>
					<span>${
       
       this.res[i].price}</span>
					<em class="addCar">加入购物车</em>
					</div>
					`;
       
				}
				this.cont.innerHTML = str;
			}
			addEvent(){
     
     
				var that = this;
				this.cont.addEventListener("click",function(eve){
     
     
					var e = eve||window.event;
					var target = e.target || e.strElement;
					if(target.className=="addCar"){
     
     
						
						that.id = target.parentNode.getAttribute("index");
						//console.log(that.id);
						that.setCookie();
					}
				})
			}
			setCookie(){
     
     
				//存cookie
				//存json,在购物车中可以保存数量,只是用一条cookie
				//由于json可以保存好多数据,这里使用json
				//第一次加入购物车直接加入
				//不是第一次
					//先判断这次点击的是新商品还是老商品
						//新商品,增加
						//老商品,增加数量
				this.goods = getCookie("goodsDECookie") ? JSON.parse(getCookie("goodsDECookie")) : [];
				console.log(this.goods);
				//第一次加入购物车直接加入
				if(this.goods.length<1){
     
     
					this.goods.push({
     
     
						id:this.id,
						num:1
					});
				}else{
     
     
					var onoff = true;
					//先判断这次点击的是新商品还是老商品
					for(var i =0;i<this.goods.length;i++){
     
     
						//老商品,增加数量
						if(this.goods[i].id === this.id){
     
     
							this.goods[i].num++;
							onoff = false;
						}
					}
					//新商品,增加
					if(onoff){
     
     
						this.goods.push({
     
     
							id:this.id,
							num:1
						})
					}
					
				}
				setCookie("goodsDECookie",JSON.stringify(this.goods));
			}
		}		
		new List;
	</script>
</html>

car.html code

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>购物车数据渲染</title>
		<style>
			img{
     
     width:100px;}
		</style>
	</head>
	<body>
		<!--cellspacing:单元格间距-->
		<table border="1" cellspacing="0" width="1000"align="center">
			<thead>
				<tr>
					<th>图片</th>
					<th>名字</th>
					<th>价格</th>
					<th>数量</th>
					<th>删除</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td colspan="5">购物车为空。。。<a href="list.html"></a></td>
					<td><img src="" alt="" /></td>
					<td></td>
					<td></td>
					<td><input type="number" min=1 /></td>
				</tr>
			</tbody>
		</table>
	</body>
	<script src="../ajax.js"></script>
	<script src="../cookie/cookie.js"></script>
	<script type="text/javascript">
		class Car{
     
     
			constructor(){
     
     
				this.url = "http://localhost/Myphp/shopping/data/goods.json";
				this.tbody = document.querySelector("tbody");
				
				this.load();
			}
			load(){
     
     
				
				ajaxGet(this.url,(res)=>{
     
     
//					console.log(res);
					this.res = JSON.parse(res);//json转换成对象数组。
//					console.log(this.res);
					this.getCookie();
				})
			}
			getCookie(){
     
     
				this.goods = getCookie("goodsDECookie") ? JSON.parse(getCookie("goodsDECookie")) : [];
				this.display();
			}
			display(){
     
     
//				console.log(this.res);
//				console.log(this.goods);
				var str = "";
				for(var i=0;i<this.res.length;i++){
     
     
					console.log(this.res[i]);
					for(var j=0;j<this.goods.length;j++){
     
     
						console.log(this.goods[j]);
						if(this.res[i].goodsId == this.goods[j].id){
     
     
//							console.log(1);
							str += `<tr index="${
       
       this.res[i].goodsId}">
										<td><img src="${
       
       this.res[i].img}"/></td>
										<td>${
       
       this.res[i].name}</td>
										<td>${
       
       this.res[i].price}</td>
										<td><input type="number" min=1 value="${
       
       this.goods[j].num}" /></td>
										<td class="delete">删除</td>
									</tr>`;
						}
					}
				}
				this.tbody.innerHTML = str;
			}
		}
		new Car;
	</script>
</html>

goods.json code

	[{
    
    
        "img":"https://img10.360buyimg.com/n7/jfs/t5617/321/1137763311/121847/b9326254/5923eb44Ndae8df59.jpg.webp",
        "name":"微软(Microsoft)Surface Pro 二合一平板电脑 12.3英寸(Intel Core i5 8G内存 256G存储 )",
        "price":"9888.00",
        "goodsId":1
    },{
    
    
        "img":"https://img13.360buyimg.com/n7/jfs/t17425/6/1117130719/77250/b4afe949/5abb0fc0Nb0fd7afd.jpg.webp",
        "name":"Apple iPad 平板电脑 2018年新款9.7英寸(128G WLAN版/A10 芯片/Touch ID MRJP2CH/A)金色",
        "price":"5999.00",
        "goodsId":2
    },{
    
    
        "img":"https://img14.360buyimg.com/n2/jfs/t22945/291/2044515279/67669/7a4a50e/5b713f0eN0caa8e0b.jpg.webp",
        "name":"微软(Microsoft)Surface Go 二合一平板电脑 10英寸(英特尔 奔腾 金牌处理器4415Y 8G内存 128G存储)",
        "price":"3738.00",
        "goodsId":3
    },{
    
    
        "img":"https://img11.360buyimg.com/n2/jfs/t5935/195/2108753717/176060/c849dcb6/593a49a3Nf9c2a052.jpg.webp",
        "name":"Apple MacBook Air 13.3英寸笔记本电脑 银色(2017新款Core i5 处理器/8GB内存/128GB闪存 MQD32CH/A)",
        "price":"5999.00",
        "goodsId":4
    }]

Guess you like

Origin blog.csdn.net/qq_38110274/article/details/103219053
Recommended