文件目录
一:封装ajax请求
let axios = {
get (url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
// 准备一个请求 url向谁请求
xhr.open('get', url);
// 监听状态,接收服务返回的数据
xhr.onreadystatechange = function () {
// ajax状态4 服务器 200
if (xhr.readyState == 4 && xhr.status == 200) {
// 接收返回值
let res = xhr.responseText;
resolve(res)
}
}
// 发送请求
xhr.send();
})
},
post (url, data) {
return new Promise(function (resolve, reject) {
//1 实例化对象
let xhr = new XMLHttpRequest();
// 2设置一个请求
xhr.open('post', url);
// 所有的post请求,必须设置参数的编码方式
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
// 3 监听请求
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 接收返回值
resolve(xhr.response)
}
}
//4 发送请求
xhr.send(data);
})
}
}
二:商品追加到页面,和添加购物车的实现
class Goods {
constructor() {
Goods.list();
}
// 获取商品信息的
// static 静态方法
// 静态方法只属于某个类
static list () {
//发送ajax请求
axios.get('http://localhost/day1012-27/cart2/server/server.php?fn=lst')
.then(res => { //res是后台返回的数据
// console.log(res);
//将数据转化为对象
let { meta, data } = JSON.parse(res);
console.log(meta, data);
//判断服务器状态
let html = '';
if (meta.status == 200) {
//数据是数组对象 取出需要拼接的数据
//需要先循环
data.forEach(ele => {
let { id, goodsName, goodsImg, price } = ele;
html += `<div class="box"><img src="${goodsImg}" alt=""><p>${goodsName}</p><span
class="goods_item_price" data-price-id="100004222715" style="">¥${price}</span><a
href="javascript:" id="InitCartUrl" class="btn-special1 btn-lg" onclick="Goods.addCart(${id},1)">
加入购物车</a></div>`;
})
//追加到页面中去
let cont = document.querySelector('#cont')
cont.innerHTML = html;
}
})
}
//添加购物车的方法
static addCart (id, num) {
console.log(id, num);
/*
购物车逻辑:
1 判断cart这个key是否存在
2 存在就判断商品是否存在
2-1 商品存在增加数量
2-2 商品不存在则新增
3 不存在则新增cart
*/
//取出local中的数据
let cartGoods = localStorage.getItem('cart');
// console.log(cartGoods);
//2 判断商品是否存在
if (cartGoods) {
cartGoods = JSON.parse(cartGoods);
//2 判断商品是否存在
//循环遍历 for in 遍历对象 这里的attr相当于id
for (let attr in cartGoods) {
if (attr == id) { //2-1商品存在增加数量
num = num + cartGoods[id]; //cartGoods[id] 是当前点击的id id是属性 取的是它的值 num没点一次传输一次 都是1
}//2-2 商品不存在则新增
}
cartGoods[id] = num; //相当于添加一个属性和属性值在 cartGoods对象中
localStorage.setItem('cart', JSON.stringify(cartGoods))
} else {
//3 不存在就新增cart
cartGoods = { [id]: num };
console.log(cartGoods);
//转化为字符串
cartGoods = JSON.stringify(cartGoods);
localStorage.setItem('cart', cartGoods);
}
}
}
new Goods();