Goods:购物车条目加减数量实现

 

list.jsp

 1 //给减号添加click事件
 2 
 3         $(".jian")
 4                 .click(
 5                         function() {
 6                             //获取cartItemId
 7                             var id = $(this).attr("id").substring(0, 32);
 8                             var quantity = $("#" + id + "Quantity").val();
 9                             //判断当前数量是否为1 如果为1就不是修改数量啦 而是删除
10                             if (quantity == 1) {
11                                 if (confirm("你是否真要删除该条目")) {
12                                     location = "/goods/CartItemServlet?method=batchDelete&cartItemIds="
13                                             + id;
14                                 }
15                             } else {
16                                 sendUpdateQuantity(id, quantity - 1);
17 
18                             }
19 
20                         });
21         //给加添加click事件
22         $(".jia").click(function() {
23 
24             var id = $(this).attr("id").substring(0, 32);
25             var quantity = $("#" + id + "Quantity").val();
26             sendUpdateQuantity(id, Number(quantity)+1);
27 
28         });
29 
30     });
31 
32     //请求服务器 修改数量  虽然那边传的是字符串 但是用ajax引擎 的json格式解析就传到result的对象格式
33 
34     function sendUpdateQuantity(id, quantity) {
35         $.ajax({
36             async : false,
37             cache : false,
38             url : "/goods/CartItemServlet",
39             data : {
40                 method : "updateQuantity",
41                 cartItemId : id,
42                 quantity : quantity
43             },
44             type : "POST",
45             dataType : "json",
46             success : function(result) {
47                 //修改数量
48                 $("#" + id + "Quantity").val(result.quantity);
49                 //修改小计
50                 $("#" + id + "Subtotal").val(result.subtotal);
51                 //重新计算总计
52                 showTotal();
53             }
54 
55         });
56 
57     }

CartItemServlet

 1 //修改数量
 2     public String updateQuantity(HttpServletRequest req, HttpServletResponse resp)
 3             throws ServletException, IOException {
 4         String cartItemId=req.getParameter("cartItemId");
 5         int quantity=Integer.parseInt(req.getParameter("quantity"));
 6         CartItem cartItem=cartItemService.updateQuantity(cartItemId, quantity);
 7                 
 8         //ajax调用返回的为json格式的对象
 9         
10         //\为转义双引号字符串
11         StringBuilder sb=new StringBuilder("{");
12         sb.append("\"quantity\"").append(":").append(cartItem.getQuantity());
13         sb.append(",");
14         sb.append("\"subtotal\"").append(":").append(cartItem.getSubtotal());
15         sb.append("}");
16         System.out.println(sb);
17         resp.getWriter().print(sb);
18         return null;
19         
20     }

 

posted @ 2015-09-07 16:31  尾巴草  阅读(670)  评论(0编辑  收藏  举报