Before, the project was deployed, play, today perfected the shopping cart to modify the number of items can be local update the corresponding total price of the function, we all know that this has to be implemented with Ajax, I did not learn Ajax, just with this small function, to simply learn Ajax knowledge.
1. Analysis of the problem
First look at the situation on the page:
Features such as, in the absence of Ajax, is generally based on user changes to find the value of the action, and then return to the new JSP page reload the entire page, complete the number of updates. But with Ajax technology, we can use Ajax technology to partially refresh the place we want to change, instead of reloading the entire page. First look at the code for the JSP part of the above figure:
<div class= "Section_container" > <!--shopping cart--> <div id= "Shopping_cart" > <div class= "message succes
S "> My shopping cart </div> <table class=" data-table cart-table "cellpadding=" 0 "cellspacing=" 0 "> <tr> <th class= "Align_center" width= "10%" > Item number </th> <th class= "Align_left" width= "35%" colspan= "2" > Product name </th> <th class= "Align_center" width= "10%" > Sales price </th> <th class= "Align_center" width= "20%" &G t; quantity </th> <th class= "Align_center" width= "15%" > Subtotal </th> <th class= "Align_center" width= "10%" > Delete </th> </tr> <c:foreach items= "${sessionscope.forder.sorders}" var= "Sorder" varstatus= "num" &G
T <tr lang= "${sorder.product.id}" > <td class= "align_center" ><a href= "#" class= "edit" >${num.count}&l t;/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> &L t;!
--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>¥<span class=" Price "id=" Total ">${sessionscope.forder.total}</span>
; </strong></td> </tr> <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&
Gt
<tr> <td width= "60%" colspan= "1" class= "Align_left Total" ><strong> totals </strong></td> <TD class= "Align_right" style= ">¥<span class=" Total "id=" Totalall "><strong>${ sessionscope.forder.total}</strong></span> </td> </tr> </tbody> </t able> <div class= "Action_buttonbar" > <font><a href= "${shop}/user/confirm.jsp" > <but ton type= "button" title= "" class= "Checkout fr" style= "Background-color: #f38256;" > Order Confirmation </button></a> </font> <font><a href= "#" > <button type= "button" Ti Tle= "" Class= "fr" > <font> empty Shopping cart </font> </button> </font> <a href= "${shop}/index.jsp" > <button type= "button" title= "" class= "C Ontinue FR "> <font> continue shopping </font> </button></a> <div style=" Clear:both ">&L
t;/div> </div> </div> </div>
Looks like a lot of appearance, in fact, the function is very simple, is to take out the corresponding data from the field to show it, we now want to achieve the function described above, first to analyze the idea:
First have to register an event: That is, modify the number of the text box that triggers the event;
In this case, we get the number of user input, judge the legitimacy of the input, because to prevent users from disorderly input;
If valid, send the data to the background via AJAX requests;
Background for the new number, call the corresponding business logic method to get new results, and through the flow back to the foreground;
When Ajax receives the results, it updates the data in the corresponding location. The whole process is over.
If illegal, the number before the modification is displayed. Don't do any processing
2. Implementation of AJAX requests
After analyzing the process, we proceeded to implement, first of all, the JS part of the code affixed to this, and then we based on the above process of detailed analysis:
<script type= "Text/javascript" > $ (function () {//1. Registration event $ (". Text"). Change (function () {//2. Validate the validity of the data var n Umber = This.value;
You can also use $ (this). Val (); isNaN (number) means to return True if (!isnan () && parseint (number) ==number && number>0) {//
If valid, synchronize the number of updates $ (this). attr ("Lang";
Finds the first parent of TR in the current tab and gets the value of the attribute, which is the ID var pid = $ (this) for the product. Parents ("Tr:first"). attr ("Lang");
Sends the AJAX request, transmits the current quantity and the product ID, returns the total price after the modification quantity $.post ("Sorder_updatesorder.action", {number:number, ' product.id ':p ID},
The function (total) {$ ("#total"). HTML (total);//All merchandise subtotal var Yunfei = $ ("#yunfei"). html ();
$ ("#totalAll"). HTML ((total*1 + yunfei*1). ToFixed (2));//All merchandise subtotal and freight and}, "text");
Calculates a subtotal for a single item, leaving the two-bit decimal var price = ($ (this). Parent (). Prev (). HTML () *number). toFixed (2);
$ (this). Parent (). Next (). HTML (price);
else {//if illegal, revert to just valid number This.value = $ (this). attr ("Lang");
}}) </script>
2.1 Registering events
We look at the code above to see that the registration event first navigates to the text box, which is positioned through the class selector, because it is a text box, so register the event with change () and define a function () in it to handle the event.
2.2 Judging data legality
Well, after registering the event, we first need to make a valid judgement on the number of user input, because the user may enter 0 or negative numbers, may have entered a decimal, or even entered a letter or other characters and so on. So to verify. isNaN (number) means that if number is not numeric and returns true, we can use this function to determine whether it is numeric or not, and to compare it to the parseint, which we have cleverly used to determine whether or not numbers are integers.
2.3 Sending Ajax requests
If the data is legitimate, after we get the data, we can send Ajax requests to the background, and we need to consider a question: What parameters to pass? First, users want to update the number, there is no doubt that the number of users input must pass through, and then the end of which goods to pass? That is, we need to obtain the user wants to modify the product ID number, know the parameters to pass, we find a way to get the ID number.
There is a problem, there may be more than one item in the user's cart, it is natural to think that if you can use a statement to get the ID of different products, it is very good, therefore, think of the text box can use the parent tag, because the different products its parent tags are the same, are the first <tr> tags , so we put the ID of the product in the lang attribute in that <tr> tag, why should we put it in the lang attribute? Because the lang attribute is basically not used, it is used to define the language, and it is not easy to use the lang attribute to conflict with other attributes ~ so that we can get the ID of the product through $ (this). Parents ("Tr:first"). attr ("Lang");
The next step is to send an AJAX request, which is sent using post, with four parameters in the Post method:
The First parameter is the action to send to
The second parameter is the parameter to pass past, using the JSON format
The third parameter is a function (result), which is used to receive data from the background through
The fourth way is to specify what type of data to receive, JSON means to receive JSON data, and text represents the receiving stream
Return from the background total is the overall price of all goods, so in function, first we get all the items based on ID and then assign value to total, Totalall is added the cost of freight, the latter tofixes (2) to maintain two decimal places. Then get a single product subtotal elements, calculate a single product subtotal, so that the front page in the absence of reload, update the part we want to update, this is the powerful Ajax place, this and the previous Easyui, Easyui is also AJAX request.
Well, about the Ajax section here is done, the following is the background of the processing just request, is for their own this project, used to record the progress of the project.
3. Background updates
The action just requested by Ajax 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 () {
//Omitting extraneous code
... Update the number of items by commodity number public
String Updatesorder () {
Forder Forder = (forder) session.get ("Forder");
Update shopping items, passed in the product.id was encapsulated in the model
Forder = Sorderservice.updatesorder (model, forder);
Calculate the new total price
forder.settotal (Forderservice.clutotal (Forder));
Session.put ("Forder", Forder);
Returns the new total price in the form of a stream
= InputStream = new Bytearrayinputstream (Forder.gettotal (). toString (). GetBytes ());
return "stream";
}
The corresponding service in the method is perfect as follows:
Sorderservice interface Public
interface Sorderservice extends baseservice<sorder> {
//Omit extraneous code
... Update the number of items by Product ID and quantity public
Forder updatesorder (Sorder sorder, Forder forder);
Sorderserviceimpl Implementation class
@Service ("Sorderservice") public
class Sorderserviceimpl extends Baseserviceimpl <Sorder> implements
Sorderservice {
//Omitting extraneous code
... @Override public
Forder updatesorder (Sorder sorder, Forder forder) {for
(Sorder temp:forder.getSorders ()) { C14/>if (Temp.getproduct (). GetId (). Equals (Sorder.getproduct (). GetId ())} {
Temp.setnumber () );
}
}
Return Forder
}
}
The final struts.xml file configuration, is the "stream" with the <global-result> inside, as follows
<global-results>
<!--save other public configuration-->
<result name= "stream" type= "stream" >
<param Name= "InputName" >inputStream</param>
</result>
</global-results>
Well, now the total price calculated in the action can be streamed to the foreground, and Ajax can be received in its function, put in the sum, and then connected to the front.
Original link: http://blog.csdn.net/eson_15/article/details/51487323
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.