购物车页面修改数量功能实现
一、实现思路
1、从页面接收两个参数,itemId,num。
2、从cookie中取所有的商品列表。
3、将页面传过来的itemId对应的商品数量设为num。
4、再将新的商品列表序列化后,返回cookie。
二、代码实现
1、jsp页面和js代码。
<div class="quantity-form" data-bind=""> <a href="javascript:void(0);" class="decrement" clstag="clickcart|keycount|xincart|diminish1" id="decrement">-</a> <input type="text" class="quantity-text" itemPrice="${cart.price}" itemId="${cart.id}" value="${cart.num }" id="changeQuantity-11345721-1-1-0"> <a href="javascript:void(0);" class="increment" clstag="clickcart|keycount|xincart|add1" id="increment">+</a> </div>
itemNumChange : function(){ $(".increment").click(function(){//+ var _thisInput = $(this).siblings("input"); _thisInput.val(eval(_thisInput.val()) + 1); $.post("/cart/update/num/"+_thisInput.attr("itemId")+"/"+_thisInput.val() + ".action",function(data){ TTCart.refreshTotalPrice(); }); }); $(".decrement").click(function(){//- var _thisInput = $(this).siblings("input"); if(eval(_thisInput.val()) == 1){ return ; } _thisInput.val(eval(_thisInput.val()) - 1); $.post("/cart/update/num/"+_thisInput.attr("itemId")+"/"+_thisInput.val() + ".action",function(data){ TTCart.refreshTotalPrice(); }); });
} refreshTotalPrice : function(){ //重新计算总价 var total = 0; $(".quantity-form .quantity-text").each(function(i,e){ var _this = $(e); total += (eval(_this.attr("itemPrice")) * 10000 * eval(_this.val())) / 10000; }); $(".totalSkuPrice").html(new Number(total/100).toFixed(2)).priceFormat({ //价格格式化插件 prefix: '¥', thousandsSeparator: ',', centsLimit: 2 }); }
2、分析js和jsp页面
2.1、请求url : /cart/update/num/{itemId}/{num}.action
2.2、请求参数:itemId、num
3、service实现
@Service public class CartServiceImpl implements CartService { @Autowired private ItemService itemService; @Value("${COOKIE_EXPIRE}") private Integer COOKIE_EXPIRE;
.... public List<CartItem> getCartLists(HttpServletRequest request) { List<CartItem> cartItemList = getCartFromCookie(request); return cartItemList; } @Override public TaotaoResult updateCartNum(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num) { List<CartItem> cartLists = getCartLists(request); for(CartItem c : cartLists) { if(c.getId().longValue() == itemId) { c.setNum(num); } } CookieUtils.setCookie(request, response, "TT_CART",JsonUtils.objectToJson(cartLists), COOKIE_EXPIRE, true); return TaotaoResult.ok(); } }
4、controller层
@Controller public class CartController { @Autowired private CartService cartService; ......
@RequestMapping("/cart/update/num/{itemId}/{num}") @ResponseBody public TaotaoResult updateCartNum(HttpServletRequest request, HttpServletResponse response, @PathVariable Long itemId,@PathVariable Integer num) { TaotaoResult result = cartService.updateCartNum(request, response, itemId, num); return result; } }