共计 2202 个字符,预计需要花费 6 分钟才能阅读完成。
流程
选择版本,
选择颜色,
加入购物车
router.js
router.get(‘/addCart’, controller.default.cart.addCart);
view
app/view/default/product_info.html
选中版本,选中颜色,然后点击加入购物车
<input class=”jrgwc” type=”button” name=”addCart” id=”addCart” value=” 加入购物车 ” />
$(function() {
$(‘#addCart’).click(function() {
var goods_id = $(‘#color_list .active’).attr(‘goods_id’);
var color_id = $(‘#color_list .active’).attr(‘color_id’);
location.href = “/addCart?goods_id=” + goods_id + ‘&color_id=’ + color_id;
})
})
controller
app/controller/default/cart.js
根据传过来的 good_id 和 color_id, 查找商品和商品颜色
async addCart() {
var goods_id = this.ctx.request.query.goods_id;
var color_id = this.ctx.request.query.color_id;
//1、获取商品信息
var goodsResult = await this.ctx.model.Goods.find({“_id”: goods_id});
var colorResult = await this.ctx.model.GoodsColor.find({“_id”: color_id});
console.log(goodsResult);
if (goodsResult.length == 0 || colorResult.length == 0) {
this.ctx.status = 404;
this.ctx.body = ‘ 错误 404’; //404
} else {
// 赠品
var goodsGiftIds = this.ctx.service.goods.strToArray(goodsResult[0].goods_gift);
var goodsGift = await this.ctx.model.Goods.find({
$or: goodsGiftIds
});
var currentData = {
_id: goods_id,
title: goodsResult[0].title,
price: goodsResult[0].shop_price,
goods_version: goodsResult[0].goods_version,
num: 1,
color: colorResult[0].color_name,
goods_img: goodsResult[0].goods_img,
goods_gift: goodsGift,
/* 赠品 */
checked: true /* 默认选中 */
}
//2、判断购物车有没有数据
var cartList = this.service.cookies.get(‘cartList’);
if (cartList && cartList.length > 0) {// 存在
//4、判断购物车有没有当前数据
if (this.service.cart.cartHasData(cartList, currentData)) {
for (var i = 0; i < cartList.length; i++) {
if (cartList[i]._id == currentData._id) {
cartList[i].num = cartList[i].num + 1;
}
}
this.service.cookies.set(‘cartList’, cartList);
} else {
// 如果购物车里面没有当前数据 把购物车以前的数据和当前数据拼接 然后重新写入
var tempArr = cartList;
tempArr.push(currentData);
this.service.cookies.set(‘cartList’, tempArr);
}
} else {
// 3、如果购物车没有任何数据 直接把当前数据写入 cookies
var tempArr = [];
tempArr.push(currentData);
this.service.cookies.set(‘cartList’, tempArr);
}
this.ctx.body = ‘ 加入购物车成功 ’;
}
}
service
app/service/cookies.js
class CookiesService extends Service {
set(key, value, expires) {
expires = expires ? expires : 24 * 3600 * 1000;
this.ctx.cookies.set(key, JSON.stringify(value), {
maxAge: expires,
httpOnly: true,
encrypt: true
})
}
get(key) {
var data = this.ctx.cookies.get(key, {
encrypt: true
});
if (data) {
return JSON.parse(data);
}
return null;
}
}
效果