Example of modifying the shopping cart using Ajax

Source: Internet
Author: User

1. Design of shopping cart

ShoppingCartItem: encapsulation of a book, including three attributes: title, quantity, and price, and corresponding getter and setter methods.

ShoppingCart: the shopping cart encapsulation class. The items is Map <String, ShoppingCartItem>, and add it to the shopping cart to obtain the total number of books in the shopping cart and the total price.

2: Add jsp to the shopping cart and add the title and price to the hyperlink

<Body> <! -- Add span to locate --> <div id = "cartstatus"> you have added <span id = "bookName"> </span> to the shopping cart, the shopping cart contains <span id = "totalBookNumber"> </span> books, the total price is <span id = "totalMoney"> </span> </div> <br> java <a href = "$ {pageContext. request. contextPath}/addToCart? Id = java & price = 100 "> Add to shopping cart </a> <br> ajax <a href =" $ {pageContext. request. contextPath}/addToCart? Id = ajax & price = 200 "> Add to shopping cart </a> <br> jquery <a href =" $ {pageContext. request. contextPath}/addToCart? Id = jquery & price = 300 "> Add to shopping cart </a> <br> </body> <! -- $ {PageContext. request. contextPath} Get the absolute path of the project -->

3: addToCart ----- servlet Design

The procedure is as follows:

1): Get the request parameter id (bookName), price, obtained from the hyperlink in the jsp page

2): Get the shopping cart object in the session. If there is no shopping cart in the session property, create a new shopping cart object and place it in the session property.

3): Add Shopping. addToCart (bookName, price) to the Shopping cart );

4): to transmit a Json object through ajax, the object includes: {"bookName" ":" totalBookNumber "," totalMoney "}. If the json object is returned from the server, the attribute name must use double quotation marks !!

5): response to the json request, response. getWriter (). print (json );

Public class AddToCartServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 1: Get the request parameter id (bookName ), price String bookName = request. getParameter ("id"); int price = Integer. parseInt (request. getParameter ("price"); // 2: Get the shopping cart object. In the session, ShoppingCart SC = (ShoppingCart) request. getSession (). getAttribute ("SC"); if (SC = null) {SC = new ShoppingCart (); request. getSession (). setAttribute ("SC", SC) ;}// 3; Add the clicked object to the shopping cart SC. addToCart (bookName, price); // 4: Json object for response preparation: {"" bookName "": "totalBookNumber ", "totalMoney"} // If a json object is returned from the server, the attribute name must use double quotation marks !! StringBuilder sBuilder = new StringBuilder (); sBuilder. append ("{"). append ("\" bookName \ ": \" "+ bookName + "\""). append (","). append ("\" totalBookNumber \ ": \" "+ SC. getTotalBookNumber () + "\""). append (","). append ("\" totalMoney \ ": \" "+ SC. getTotalMoney () + "\""). append ("}"); // response to the json request response. setContentType ("text/javascript"); response. getWriter (). print (sBuilder. toString () ;}} the StringBuilder can be used to concatenate JSON strings to simplify the implementation by using a third-party open-source Jackson: String jsonStr = null; ObjectMapper objectMapper = new ObjectMapper (); jsonStr = objectMapper. writeValueAsString (SC );

4: ajax receives the parameter {"bookName" ":" totalBookNumber "," totalMoney "} from the server "}

Steps:

1): added a click response function to add the hyperlink to the shopping cart and canceled the default behavior (return false)

2): Load JSON data through http get requests. $. GetJSON (url, [data], [callback])

Prepare url. agrs and display the content in the shopping cart on the Jsp page in the callback function.

3): Use the hide () and show () methods in jquery to determine whether to use the shopping cart first. If it is used for the first time, the jsp page does not display the shopping cart.

<Head> <! -- $ {PageContext. request. contextPath} gets the absolute path of the project --> <script type = "text/javascript" src = "$ {pageContext. request. contextPath}/scripts/jquery-1.7.2.js "> </script> <script type =" text/javascript ">$ (function () {var isHasCart =" $ {sessionScope. SC = null} "; if (isHasCart =" true ") {$ (" # cartstatus "). hide (); // hide the displayed element} else {$ ("# cartstatus "). show (); // display hidden matching elements $ ("# bookName "). text ("$ {sessionScope. SC. bookName} "); $ (" # totalBookNumber "). text ("$ {sessionScope. SC. totalBookNumber} "); $ (" # totalMoney "). text ("$ {sessionScope. SC. totalMoney} ") ;}$ (" "). click (function () {$ ("# cartstatus "). show (); var url = this. href; // url property var agrs = {"time": new Date ()}; // timestamp $. getJSON (url, agrs, function (data) {$ ("# bookName "). text (data. bookName); $ ("# totalBookNumber "). text (data. totalBookNumber); $ ("# totalMoney "). text (data. totalMoney) ;}); return false ;}) ;}</script> 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.