I have deployed the project and played it. Today I have improved the function of modifying the quantity of products in the shopping cart to partially update the corresponding total price. Everyone knows that this has to be implemented with Ajax. I haven't learned Ajax before, and I just happened to use this small function to simply learn Ajax knowledge.
1. Analysis of the problem
Let’s take a look at the situation on the page:
The function is as above. Before Ajax is not available, you usually look for Action based on the user's modified value, and then return to the new jsp page to reload the entire page to complete the update of the numbers. But with Ajax technology, we can use Ajax technology to partially refresh the changes to the place we want to change, instead of reloading the entire page. First, let’s take a look at the code of the jsp part corresponding to the above picture:
<div> <!-- Shopping Cart--> <div id="shopping_cart"> <div>My Shopping Cart</div> <table cellpadding="0" cellpacing="0"> <tr> <th>Product Number</th> <th colspan="2">Product Name</th> <th>Sales Price</th> <th>Quantity</th> <th>Subtotal</th> <th>Delete</th> </tr> <c:forEach items="${sessionScope.forder.sorders }" var="sorder" varStatus="num"> <tr lang="${sorder.product.id}"> <td><a href="#">${num.count }</a></td> <td><img src="${shop}/files/${sorder.product.pic}" /></td> <td><a href="#">${sorder.name }</a></td> <td>${sorder.price }</td> <td> <!-- Text box--> <input style="height: 20px;" value="${sorder.number }" lang="${sorder.number }"> </td> <td>${sorder.price*sorder.number }</td> <td><a href="#"></a></td> </tr> </c:forEach> </table> <!-- Checkout--> <div> <table id="totals-table"> <tbody> <tr> <td colspan="1"><strong> Subtotal</strong></td> <td style=""><strong>¥<span id="total">${sessionScope.forder.total}</span> </strong></td> </tr> <tr> <td colspan="1">Freight</td> <td style="">¥<span id="yunfei">0.00</span></td> </tr> <tr> <td colspan="1"><strong>Total</strong></td> <td style="">¥<span id="totalAll"><strong>${sessionScope.forder.total}</strong></span> </td> </tr> </tbody> </table> <div> <font><a href="${shop}/user/confirm.jsp"> <button type="button" style="background-color: #f38256;">Order confirmation</button></a> </font> <font><a href="#"> <button type="button"> <font>Clear the cart</font> </button> </font> <a href="${shop}/index.jsp"> <button type="button"> <font>Continue shopping</font> </button></a> <div style="clear:both"></div> </div> </div> </div> </div> </div> </div> </div>It looks like a lot, but the function is actually very simple. It just takes out the corresponding data from the domain to display it. If we want to implement the functions described above, let’s analyze the ideas first:
First, you have to register an event: that is, the event triggered by the text box in the number is modified;
In this event, we get the number input by the user and judge the legality of the input, because we must prevent the user from entering randomly;
If legal, send data to the background via Ajax request;
The background calls the corresponding business logic method to obtain new results for a new number and returns it to the foreground through the stream;
After Ajax receives the result, it updates the data at the corresponding location. The whole process is over.
If it is illegal, the number before modification is displayed. No treatment is done
2. Implementation of Ajax requests
After analyzing the process, we will start to implement it. First, paste the code of the js part here, and then we analyze it in detail based on the above process:
<script type="text/javascript"> $(function(){ //1. Register event $(".text").change(function(){ //2. Verify the validity of the data var number = this.value; // You can also use $(this).val(); //isNaN(number) means that if number is not a number, return true if(!isNaN(number) && parseInt(number)==number && number>0){ //If it is legal, synchronously updated number $(this).attr("lang", number); // Find the parent node of the current tag with the first tr, and then get the value of the attribute lang, that is, the id of the product var pid = $(this).parents("tr:first").attr("lang"); //Send an Ajax request, transmit the current quantity and the id of the product, and return the total price after the modified quantity $.post("sorder_updateSorder.action", {number:number, 'product.id':pid}, function(total){ $("#total").html(total); //Subtotal of all products var yunfei = $("#yunfei").html(); $("#totalAll").html((total*1 + yunfei*1).toFixed(2)); //Sum of all products subtotal and freight }, "text"); // Calculate the subtotal of a single product, retaining two decimal places var price = ($(this).parent().prev().html()*number).toFixed(2); $(this).parent().next().html(price); } else { // If it is illegal, restore to the number that just legal this.value = $(this).attr("lang"); } }) }) })</script>2.1 Registration Event
We can see that the registration event must first be positioned to this text box. Here it is positioned through the class selector. Because it is a text box, change() is used to register the event, and then define a function() function in it to handle the event.
2.2 Judge the legality of data
OK, after registering the event, we must first make a judgment on the legality of the number entered by the user, because the user may enter 0 or negative numbers, may enter decimals, or even letters or other characters, etc. So verification is required. isNaN(number) means that if number is not a number, it returns true. We can use this function to determine whether it is a number; parseInt(number) means rounding the array and then comparing it with itself. We cleverly use this to determine whether number is an integer.
2.3 Send Ajax request
If the data is legal, after we obtain the data, we can send an Ajax request to the background. We need to consider a question: What parameters do we need to pass? First of all, if the user wants to update the quantity, there is no doubt that the numbers entered by the user must be transmitted over. Secondly, which product should be transmitted? In other words, we need to obtain the id number of the product that the user wants to modify. After knowing the parameters to be transmitted, we can find a way to obtain the id number.
There is a question here. Users may have more than one product in their shopping cart. Naturally, they will think that it would be great if they can get the id of different products with a statement. Therefore, they thought of using the parent tag of the text box. Because the parent tags of different products are the same, they are the first <tr> tags, so we put the id of the product in the lang attribute in the <tr> tag, why put it in the lang attribute? Because the lang attribute is basically not used, it is used to define languages, and using the lang attribute is not easy to conflict with other attributes~ In this way, we can obtain the product id through $(this).parents("tr:first").attr("lang");
Next, start sending Ajax requests, sending them using post method. There are four parameters in the post method:
The first parameter is the Action to be sent to
The second parameter is the parameter to be passed, using the json format
The third parameter is a function(result), which is used to receive data passing through the background.
The fourth method is to specify what type of data to be received. Json means receiving json data, and text means receiving stream
The total returned from the background is the total price of all products, so in the function, first we get the elements of all products subtotals based on the id and assign the value to total. TotalAll is the total price with the freight added. The latter toFixes(2) means retaining two decimal places. Then get the element of a subtotal of a single product and calculate the subtotal of a single product. In this way, the front desk page updates the part we want to update without reloading. This is the powerful part of Ajax. This is the same as the previous EasyUI, which is also an Ajax request.
Okay, the Ajax part is introduced here. The following is the background processing of the request just now, which is for my own project and is used to record the project progress.
3. Backend update
The action requested by Ajax just now is the updateSorder() method in SortedAction, so we go to SorderAction to complete the updateSorder() method:
@Controller@Scope("prototype")public class SorderAction extends BaseAction<Sorder> { public String addSorder() { //Omit irrelevant code... //Update the quantity of products according to the product number public String updateSorder() { Forder forder = (Forder) session.get("forder"); //Update the shopping item, the product.id passed in is encapsulated into the model forder = sorderService.updateSorder(model, forder); //Calculate the new total price forder.setTotal(forderService.cluTotal(forder)); session.put("forder", forder); //Return the new total price in the form of a stream inputStream = new ByteArrayInputStream(forder.getTotal().toString().getBytes()); return "stream"; }}The corresponding methods in the Service are improved as follows:
//SorderService interface public interface SorderService extends BaseService<Sorder> { //Save irrelevant code... //Update product quantity according to product id and quantity public Forder updateSorder(Sorder soorder, Forder forder);}//SorderServiceImpl implementation class @Service("sorderService")public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements SorderService { //Omit irrelevant code... @Override public Forder updateSorder(Sorder soorder, Forder forder) { for(Sorder temp : forder.getSorders()) { if(temp.getProduct().getId().equals(sorder.getProduct().getId())) { temp.setNumber(sorder.getNumber()); } } return forder; }}Finally, the configuration in the struts.xml file is to assign "stream" to <global-result>, as follows
<global-results> <!-- Save other public configurations--> <result name="stream" type="stream"> <param name="inputName">inputStream</param> </result></global-results>
Okay, now the total price calculated in the Action can be transmitted to the front desk through the form of a stream, Ajax can be received in its function, placed in total, and connected to the front.
Original link: http://blog.csdn.net/eson_15/article/details/51487323
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.