Use Ajax technology to partially refresh the product quantity and total price instance code, ajax product quantity

Source: Internet
Author: User

Use Ajax technology to partially refresh the product quantity and total price instance code, ajax product quantity

1. Problem Analysis

Let's take a look at the situation on the page:

 

Before Ajax is available, the user usually finds the Action based on the value modified by the user, and then returns a new jsp page to reload the entire page to update the number. However, with the Ajax technology, we can use the Ajax technology to partially refresh the changes, rather than reload the entire page. First, let's take a look at the corresponding jsp code:

<Div class = "section_container"> <! -- Shopping cart --> <div id = "shopping_cart"> <div class = "message success"> my shopping cart </div> <table class = "data-table cart-table" cellpadding = "0" cellspacing = "0"> <tr> <th class = "align_center" width = "10%"> item No. </th> <th class = "align_left" width = "35%" colspan = "2"> item name </th> <th class = "align_center" width = "10%"> sales price </th> <th class = "align_center" width = "20%"> quantity </th> <th class = "align_center" width = "15%"> subtotal </th> <th class = "align_c Enter "width =" 10% "> Delete </th> </tr> <c: forEach items =" $ {sessionScope. forder. sorders} "var =" sorder "varStatus =" num "> <tr lang =" $ {sorder. product. id} "> <td class =" align_center "> <a href =" # "class =" edit ">$ {num. count} </a> </td> <td width = "80px">  </td> <td class =" align_left "> <a class =" pr_name "href =" # "> $ {sorder. name} </a> </td> <td class = "align _ Center vline ">$ {sorder. price} </td> <td class =" align_center vline "> <! -- Text box --> <input class = "text" style = "height: 20px;" value = "$ {sorder. number} "lang =" $ {sorder. number} "> </td> <td class =" align_center vline ">$ {sorder. price * sorder. number} </td> <td class = "align_center vline"> <a href = "#" class = "remove"> </a> </td> </tr> </c: forEach> </table> <! -- Settlement --> <div class = "totals"> <table id = "totals-table"> <tbody> <tr> <td width = "60%" colspan = "1" class = "align_left"> <strong> subtotal </strong> </td> <td class = "align_right" style = ""> <strong> ¥ <spanclass = "price" id = "total" >$ {sessionScope. forder. total }</span> </strong> </td> </tr> <td width = "60%" colspan = "1" class = "align_left"> freight </td> <td class = "align_right" style = ""> ¥ <span class = "price" id = "yunfei"> 0.00 </span> </td> </tr> <td width = "60%" colspan = "1" class = "align_left total"> <strong> total </strong> </td> <td class = "align_right" style = ""> ¥ <span class = "total" id = "totalAll"> <strong >$ {sessionScope. forder. total }</strong> </span> </td> </tr> </tbody> </table> <div class = "action_buttonbar"> <font> <a href = "$ {shop}/user/confirm. jsp "> <button type =" button "title =" "class =" checkout fr "style =" background-color: # f38256; "> Confirm order </button> </a> </font> <a href =" # "> <button type =" button "title =" "class = "fr"> <font> clear the shopping cart </font> </button> </font> <a href = "$ {shop}/index. jsp "> <button type =" button "title =" "class =" continue fr "> <font> continue shopping </font> </button> </a> <div style = "clear: both "> </div>

It looks like a lot. In fact, the function is very simple, that is, to display the corresponding data from the domain. If we want to implement the functions described above, let's first analyze the ideas:

First, you must register an event: the event triggered by modifying the number of text boxes;

In this event, we get the number of user inputs to determine the validity of the input, because it is necessary to prevent user input from disorder;

If it is valid, send data to the background through Ajax requests;

The backend calls the corresponding business logic method to obtain the new result based on the new quantity, and returns the result to the front end through the over-traffic;

After receiving the result, Ajax updates the data at the corresponding location. The entire process is complete.

If it is invalid, the number before modification is displayed. No Processing

2. Ajax request implementation

After analyzing the process, let's proceed with implementation. First, paste the js Code here, and then 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) indicates that if number is not a number, true if (! IsNaN (number) & parseInt (number) = number & number> 0) {// number of synchronously updated values (this) if valid ). attr ("lang", number); // find the first parent node in the current tag that is tr, and obtain the value of the attribute lang, that is, the product's idvar pid =$ (this ). parents ("tr: first "). attr ("lang"); // sends an Ajax request, transmits the current quantity and product id, and returns the total price after the modified quantity $. post ("sorder_updateSorder.action", {number: number, 'product. id': pid}, function (total) {$ ("# total" ).html (total); // All goods subtotal var yunfei =$ ("# yunfei" ).html (); $ ("# totalAll" ).html (total * 1 + yunfei * 1 ). toFixed (2); // sum of all goods subtotal and freight}, "text"); // calculate the subtotal of a single commodity, retain two decimals var price = (%(this%.parent(%.prev(%.html () * number).tofixed(2);((this).parent().next().html (price);} else {// if it is illegal, restore it to the valid number just now this. value = $ (this ). attr ("lang") ;}})} </script>

2.1 registration event

We can see from the code above that the registration event must first be located in this text box, which is located through the class selector. Because it is a text box, we use change () to register this event, define a function () in it to process the event.

2.2 determine Data Validity

Well, after registering the event, we must first determine the validity of the number of user input, because the user may have input 0 or negative numbers, and may have input decimals, it even contains letters or other characters. Therefore, verification is required.

IsNaN (number) indicates that if number is not a number, it returns true. We can use this function to determine whether the number is a number. parseInt (number) indicates the array is rounded up, then compare it with itself, we skillfully use this to determine whether the number is an integer.

2.3 send Ajax requests

If the data is valid, we can send an Ajax request to the background after obtaining the data. We need to consider the following question: what parameters need to be passed? First, the user wants to update the quantity. There is no doubt that the number entered by the user must be passed in. Which product is next? That is to say, we need to get the ID number of the item that the user wants to modify. After knowing the parameter to be passed, we can find a way to get the ID number.

There is a problem here. There may be more than one item in the user's shopping cart. It is natural to think that if you can use a statement to get the IDs of different items, it would be very good. Therefore, the parent label of the text box can be used. Because the parent labels of different products are the same, they are the first <tr> label, so we put the product id in the lang attribute of the <tr> tag. Why should we put the product id in the lang attribute? This is because the lang attribute is basically not used. It is used to define the language, and the lang attribute cannot conflict with other attributes ~ In this way, we can get the product id through $ (this). parents ("tr: first"). attr ("lang.

Next, we start to send Ajax requests and use post. The post method has four parameters:

The first parameter is the Action to be sent

The second parameter is the parameter to be passed in, in json format.

The third parameter is a function (result), which is used to receive data transmitted through the background.

The fourth method is to specify the type of data to be received. json indicates that json data is received, and text indicates that the received stream is received.

The total value returned from the backend is the total price of all commodities. Therefore, in the function, we first obtain the elements of all commodity subtotal Based on the id and then assign the value to total. totalAll adds the total price of freight, the next toFixes (2) indicates that two decimal places are retained. Then we get the elements of a single commodity subtotal and calculate the subtotal of a single commodity. In this way, the front-end page updates the part we want to update without re-loading, this is where Ajax is powerful. Like EasyUI, EasyUI is also an Ajax request.

Well, the Ajax section has been described here. The following is the background processing request for this project, which is used to record the project progress.

3. Background updates

The action requested by Ajax is the updateSorder () method in SortedAction, so we can complete the updateSorder () method in SorderAction:

@ Controller @ Scope ("prototype") public class SorderAction extends BaseAction <Sorder> {public String addSorder () {// omitting irrelevant code ...... // Update the number of items according to the product ID. public String updateSorder () {Forder forder = (Forder) session. get ("forder"); // update the shopping item and the imported product. id is encapsulated in 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 inputStream = new ByteArrayInputStream (forder. getTotal (). toString (). getBytes (); return "stream ";}}

The methods in the corresponding Service are improved as follows:

// SorderService interface public interface SorderService extends BaseService <Sorder> {// saves irrelevant code ...... // Update the public Forder updateSorder (Sorder sorder, Forder forder) according to the item id and quantity;} // SorderServiceImpl implementation class @ Service ("sorderService ") public class SorderServiceImpl extends BaseServiceImpl <Sorder> implementsSorderService {// omitting irrelevant code ...... @ Overridepublic Forder updateSorder (Sorder sorder, Forder forder) {for (Sorder temp: forder. getSorders () {if (temp. getProduct (). getId (). equals (sorder. getProduct (). getId () {temp. setNumber (sorder. getNumber () ;}} return forder ;}}

Finally, in the struts. xml file, "stream" is configured in <global-result>, as follows:

<Global-results> <! -- Save other public configurations --> <result name = "stream" type = "stream"> <param name = "inputName"> inputStream </param> </result> </global -results>

Now, the total price calculated in the Action can be transmitted to the front-end in the form of a stream, Ajax can receive it in its function, put it in total, and connect it to the front.

The above is a wonderful example of how to use Ajax technology to partially refresh the product quantity and total price instance code. I hope it will help you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.