改動購物項圖書數量的Ajax處理

來源:互聯網
上載者:User

標籤:int   att   .com   function   public   other   nan   cond   war   

一、cart.jsp頁面

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><base href="http://${pageContext.request.serverName }:${pageContext.request.serverPort }${pageContext.request.contextPath }/" /><title>Insert title here</title><script type="text/javascript" src="script/jquery-1.7.2.js"></script><script type="text/javascript">$(function(){//★給全部刪除連結加入點擊事件$(".delete").click(function(){if(!window.confirm("你確定要刪除該購物項嗎?")){return false; //不讓連結提交}});//給全部顯示書的數量的輸入框加入失去焦點的事件$(".count").blur(function(){var count =this.value;//得到輸入框中的數值if(isNaN(count)){count=1;}count=count*1;//→轉為number類型if(count<=0){count=1;}var bookId=this.id;//this代表了當前的輸入框中的內容//在這裡須要在其變化之前儲存下來以便於在function中使用var inputEle=this; //它是一個dom對象//window.location.href = "${pageContext.request.contextPath}/client/CartServlet?

method=update&count="+count+"&bookId="+bookId;//★改動購物項圖書數量的Ajax處理★ 這個時候須要發送Ajax請求var path="client/CartServlet"; //上面加了base標籤var params={method:"update",count:count,bookId:bookId};//data的資料類型{count:2,itemPrice:20,totalCount:5,totalPrice:50}var success=function(data){//→須要更新四處//得到總數量$("#totalCount").html(data.totalCount);//得到總價$("#totalPrice").html(data.totalPrice);//更新購物項中的圖書數量inputEle.value=data.count;//將資料放進去//得到小計$(inputEle).parent().parent().find(".itemPrice").html(data.itemPrice);}$.post(path,params,success,"json");});//給<button>+</button>加入點擊事件 $(".increase").click(function(){//得到 數量首先,先找button的父元素,再找子項目var $countEle=$(this).parent().find("input");var count=$countEle.val();//得到文字框中的值 count=count*1+1;//轉為number類型後再做運算\//擷取書的idvar bookId=$countEle.attr("id"); //如今改為發送Ajax請求var path="client/CartServlet";var params={method:"update",count:count,bookId:bookId};var success=function(data){$("#totalCount").html(data.totalCount);$("#totalPrice").html(data.totalPrice);//更新書的數量$countEle.val(data.count);//得到小計$countEle.parents("tr").find(".itemPrice").html(data.itemPrice);};$.post(path,params,success,"json");}); //給<button>-</button>加入點擊事件$(".decrease").click(function(){//得到數量var $countEle = $(this).parent().find("input");var count = $countEle.val();//鏈式調用count = count*1-1;if(count<=1){count=1;} //書的idvar bookId = $countEle.attr("id");//請求//window.location.href = "${pageContext.request.contextPath}/client/CartServlet?method=update&count="+count+"&bookId="+bookId;//改為Ajax請求。。。。var path="client/CartServlet";var params={method:"update",count:count,bookId:bookId};var success=function(data){$("#totalCount").html(data.totalCount);$("#totalPrice").html(data.totalPrice);//更新書的數量$countEle.val(data.count);//找當前行的小計$countEle.parents("tr").find(".itemPrice").html(data.itemPrice);};$.post(path,params,success,"json");});});</script></head><body><center><h2>我的購物車</h2><c:choose><c:when test="${empty CART || empty CART.map }">購物車裡面還沒有書,馬上去<a href="client/BookClientServlet?

method=getPageInCondition">購物</a></c:when><c:otherwise><table border="1" cellpadding="10" cellspacing="0"><tr><td>書名</td><td>單價</td><td>數量</td><td>小計</td><td>操作</td></tr><c:forEach items="${CART.map }" var="entry"><tr><td>${entry.value.book.bookName}</td><td>${entry.value.book.price}</td><td><button class="decrease" <%-- ${entry.value.count<=1 ?

‘disabled="false"‘ : ‘‘} --%>>-</button><input id="${entry.key}" class="count" type="text" value="${entry.value.count}" style="width: 30px;"/><button class="increase">+</button></td><td ><span class="itemPrice">${entry.value.itemPrice}</span></td><td><a class="delete" href="client/CartServlet?method=delete&bookid=${entry.key}">刪除</a></td></tr></c:forEach><tr><td><a id="clear" href="client/CartServlet?method=clear" >清空購物車</a></td><td><ahref="client/BookClientServlet?method=getPageInCondition">繼續購物</a></td><td>共<span id="totalCount">${CART.totalCount }</span>本書</td><td>總價:<span id="totalPrice">${CART.totalPrice }</span>元</td><td><a href="client/OrderServlet?method=listAllAddress">去結算</a></td></tr></table></c:otherwise></c:choose></center></body></html>


二、改動CartServlet

package com.atguigu.bookstore.servlet.client;import com.atguigu.bookstore.bean.Book;import com.atguigu.bookstore.fun.Cart;import com.atguigu.bookstore.service.impl.BookServiceImpl;import com.atguigu.bookstore.service.impl.CartServiceImpl;import com.atguigu.bookstore.service.inter.BookService;import com.atguigu.bookstore.service.inter.CartService;import com.atguigu.bookstore.servlet.BaseServlet;import com.atguigu.bookstore.utils.WebUtils;import com.google.gson.Gson;import java.io.IOException;import java.util.HashMap;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class CartServlet extends BaseServlet {private static final long serialVersionUID = 1L;CartService cartService=new CartServiceImpl();BookService bookService=new BookServiceImpl();protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("add....");String bookid = request.getParameter("bookid");Book book = bookService.getBookById(bookid);Cart cart = WebUtils.getCart(request);cartService.add(book, cart);//要得到這種資料{"bookName":"java", "totalCount": 2}怎麼得?String bookName = book.getBookName();int totalCount = cart.getTotalCount();//使用Gson能夠得到以上類型的資料,可是須要一個源,這個僅僅有map和//src是一個一般對象或map對象。在這裡僅僅能用map對象。由於假設是一般對象,所須要一個類中包括不了這2種屬性,還得又一次定義類,挺麻煩的//而src是map對象時就不須要在又一次定義類了,Map<String, Object>map=new HashMap<String, Object>();map.put("bookName", bookName); //取資料的時候是data.bookName;map.put("totalCount", totalCount);String jsonStr=new Gson().toJson(map);response.setContentType("text/json;charset=utf-8");response.getWriter().write(jsonStr);}protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("delete...");String bookid = request.getParameter("bookid");Cart cart = WebUtils.getCart(request);cartService.deleteItem(Integer.parseInt(bookid), cart);WebUtils.myForward(request, response, "/client/book/cart.jsp");}protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("update....");String count = request.getParameter("count");String bookId = request.getParameter("bookId");Map<String, Object>map=cartService.updateCount(Integer.parseInt(bookId),Integer.parseInt(count), WebUtils.getCart(request));//WebUtils.myForward(request, response, "/client/book/cart.jsp"); //不用這種方式了//要返回的資料類型:{count:2,itemPrice:20,totalCount:5,totalPrice:50},那麼怎樣得到呢?能夠更改updateCount方法,使其返回一個map集合String json = new Gson().toJson(map);response.setContentType("text/json;charset=utf-8");response.getWriter().write(json);}protected void clear(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("clear....");cartService.clear(WebUtils.getCart(request));WebUtils.myForward(request, response, "/client/book/cart.jsp");}}

三、改動CartServiceImpl

<span style="white-space:pre"></span>@Overridepublic Map<String, Object> updateCount(int BookId, int count, Cart cart) {Map<String, Object>map=new HashMap<String, Object>();CartItem cartItem = cart.getMap().get(BookId);cartItem.setCount(count);//{count:2,itemPrice:20,totalCount:5,totalPrice:50},map.put("count", count);map.put("itemPrice", cartItem.getItemPrice());map.put("totalCount", cart.getTotalCount());map.put("totalPrice", cart.getTotalPrice());return map;}


改動購物項圖書數量的Ajax處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.