Application of AJAX technology to achieve local refresh of the number of goods and total price instance code _ajax related

Source: Internet
Author: User
Tags button type numeric

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 Success" > 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%" > 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" > <tr lang= "$ {} "> <td class=" align_center "><a href=" # "class=" edit ">${num.count}</a></ td> <td width= "80px" > <td class= "align_left" ><a class= "Pr_name" href= "#" >${}</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>¥<span class=" Price "id=" 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> <tr> <td width= "60%" colspan= "1" class= "Align_left Total "><strong> totals </strong></td> <td class=" align_right "style=" >¥<span class=
"Id=" Totalall "><strong>${}</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; " > Order Confirmation </button></a> </font> <font><a href= "#" > <button type= "button" title= "" Class= "FR" > <font> empty 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> </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. Verify the validity of the data
var number = This.value;//You can also use $ (this). Val ();
isNaN (number) means to return the true if numbers are not digits
(!isnan (&& parseint (number) ==number && number>0) { 
//if valid, sync updated
$ (this). attr ("Lang", number);
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, ' ':p ID},
function (total) { 
$ (' #total '). HTML (the 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");}

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:

@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 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

<!--save other public configuration-->
<result name= "stream" type= "stream" >
<param Name= "InputName" >inputStream</param>

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.

The above is a small set to introduce the magical use of Ajax technology to refresh the local number of products and Total Price example code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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: 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.