概述
Cookie
什么是Cookie?
Cookie 是一些数据, 存储于你电脑上的文本文件中。
当 web 服务器向浏览器发送 web 页面时,在连接关闭后,服务端不会记录用户的信息。Cookie 的作用就是用于解决 “如何记录客户端的用户信息”:当用户访问 web 页面时,他的名字可以记录在 cookie 中。在用户下一次访问该页面时,可以在 cookie 中读取用户访问记录。
它的作用是什么呢?
首先需要知道,HTTP协议。http协议是网页传输协议,是超文本传输协议,无状态协议,而cookie是会话跟踪技术,就是用来记录http的状态的。
记录在哪?
记录在浏览器的缓存里,有一些限制,如下:
大小限制:4K±
数量限制:50±
时间限制:默认关闭浏览器就清除(会话级)
读取限制:不允许跨域,(路径,浏览器)
怎么记录呢?
这就涉及到了我们要说的重点了。cookie的用法。
核心操作在cookie的值的书写
cookie的值的要求:
key和value的格式:如:name=val
还要有配置信息:配置信息主要是如下两个:
有限期:expires
路径:path
配置信息和cookie的信息之间用;号隔开
cookie的增删改查
1、获取cookie的方式
document.cookie
2、设置cookie,也就是给cookie设置值。
document.cookie = "asdasd"
3、修改cookie,也就是给cookie设置新的值,没有那么复杂
document.cookie = "user=adasda;path=/1911";
4、删除cookie:过期时间,主动过期,可以都把有限期设置为昨天,这样就不用每次再思考了。
var d = new Date();
d.setDate(d.getData()-1);
document.cookie = "user=admin;expires="+d+";path=/";
document.cookie = "cookie的信息,将有限期设置为昨天"
cookie的封装
cookie的封装用处是很广的,大家需要牢记,(即使不会自己书写,可以总结出来保存下以备不时之需哦)
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
})
}
获取cookie的封装
//获取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"));
好多人即使了解到了cookie的封装,但是由于不是自己写出来的只是总结而已,可能不会用,我教大家几种简单用法,大家可以举一反三。
1、设置没有地址的cookie
setCookie("hah","jquba");
2、设置有有限期和地址的cookie
setCookie("user","admin",{
expires:4,
path:"/Myphp"
});
3、获取cookie
getCookie("key")
4、删除cookie
可以在浏览器里直接删除,也可以通过调用删除cookie的封装函数
removeCookie("key");
//或,下面的是删除有地址的cookie
removeCookie("user",{
path:"/Myphp"
})
cookie的应用,购物车
这是一个比较典型的cookie应用的实例,(要在服务器上运行哦,本地或者网上都可以。)
list.html代码
<!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代码
<!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代码
[{
"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
}]
最后
以上就是孝顺小鸽子为你收集整理的几段代码几行解析教你读懂cookieCookie的全部内容,希望文章能够帮你解决几段代码几行解析教你读懂cookieCookie所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复