1. Problem analysis

Take a look at the page first:


The functions are as above. Before AJAX is available, the user usually finds the action according to the value modified by the user, and then returns to the new JSP page to reload the whole page to complete the digital update. However, with Ajax technology, we can use ajax technology to refresh the parts to be changed, instead of reloading the whole page. First of all, take a look at the corresponding JSP code in the figure above:

<! -- shopping cart -- >
< div > My Cart < / div >
<table cellpadding="0" cellspacing="0">
< th width = "10%" > item number < / th >
< th width = "35%" colSpan = "2" > Product Name < / th >
< th width = "10%" > sales price < / th >
< th width = "20%" > quantity < / th >
< th width = "15%" > subtotal
< / width > < 10% >
<c:forEach items="${sessionScope.forder.sorders }" var="sorder" varStatus="num">
<tr lang="${sorder.product.id}">
<td><a href="#">${num.count }</a></td>
<td width="80px"><img src="${shop}/files/${sorder.product.pic}" width="80" height="80" /></td>
<td><a href="#">${sorder.name }</a></td>
<td>${sorder.price }</td>
<! -- text box -- >
<input style="height: 20px;" value="${sorder.number }" lang="${sorder.number }"> 
<td>${sorder.price*sorder.number }</td>
<td><a href="#"></a></td>
<! -- Settlement -- >
< TD width = "60%" colSpan = "1" > < strong > subtotal</td>
<td style=""><strong>¥<span
< TD width = "60%" colSpan = "1" > freight</td>
<td style="">¥<span>0.00</span></td>
< TD width = "60%" colSpan = "1" > < strong > total < / strong > total</td>
<td style="">¥<span><strong>${sessionScope.forder.total}</strong></span>
<font><a href="${shop}/user/confirm.jsp">
< button type = "button" title = "style =" background color: "f38256;" > order confirmation < / button ></a>
<font><a href="#">
<button type="button" title="">
< font > empty shopping cart
<a href="${shop}/index.jsp">
<button type="button" title="">
< font > continue shopping
<div style="clear:both"></div>

It looks like a lot of things. In fact, the function is very simple, which is to take out the corresponding data from the domain and display it. If we want to realize the functions described above, we will first analyze the ideas:

First, you have to register an event: the event triggered by the textbox where the quantity is changed;

In this event, we get the number of user input and judge the legitimacy of the input, because it is necessary to prevent the user from inputting randomly;

If it is legal, send the data to the background through Ajax request;

The background calls the corresponding business logic method to get the new result according to the new quantity, and returns it to the foreground through the flow;

After receiving the results, AJAX updates the data in the corresponding location. The whole process is finished.

If it is illegal, the number before modification is displayed. Don’t do anything about it

2. Implementation of Ajax request

After analyzing the process, we will start to implement it. First, paste the JS code here, and then we will analyze it in detail according to the above process

<script type="text/javascript">
//1. Registration events
//2. Verify the validity of the data
var number =  this.value ; // you can also use $(this). Val();
//IsNaN (number) means to return true if number is not a number
if(!isNaN(number) && parseInt(number)==number && number>0){ 
//If legal, the number of synchronized updates
$(this).attr("lang", number);
//Find the parent node of TR in the current tag, and then get the value with the attribute Lang, that is, the ID of the product
var pid = $(this).parents("tr:first").attr("lang");
//Send an Ajax request, transfer the current quantity and commodity ID, and return the total price after the modified quantity
{number:number, 'product.id':pid},
$("total"). HTML (total); // subtotal of all items
var yunfei = $("#yunfei").html();
$("ා totalall"). HTML ((total * 1 + Yunfei * 1). ToFixed (2)); // sum of subtotal of all goods and freight
}, "text");
//Calculate the subtotal of a single commodity with two decimal places
var price = ($(this).parent().prev().html()*number).toFixed(2);
} else {
//If it is illegal, it will be restored to the number just legal
this.value = $(this).attr("lang");

2.1 registration events

We can see from the above code that the registration event should be located to this text box first. Here, it is located through the class selector. Because it is a text box, change() is used to register the event, and then a function() function is defined to handle the event.

2.2 judging the validity of data

Well, after registering the event, we first need to judge the validity of the number entered by the user, because the user may have entered 0 or negative numbers, decimal numbers, or even letters or other characters. So we need to verify.

IsNaN (number) means that if number is not a number, it will return true. We can use this function to judge whether it is a number; parseInt (number) means to round the array and compare it with itself. We skillfully use this function to judge whether number is an integer.

2.3 sending Ajax requests

If the data is legal, we can send Ajax requests to the background after obtaining the data. We need to consider one question: what parameters do we need to pass? First of all, the user wants to update the quantity. Undoubtedly, the number entered by the user must be passed on. Secondly, which commodity is to be transferred? That is to say, we need to get the ID number of the product that the user wants to modify. After knowing the parameters to be transferred, we can find a way to get the ID number.

There is a problem here. Users may have more than one product in their shopping cart. Naturally, they will think that it would be very good if they can get the ID of different products with one statement. Therefore, they think of using the parent label of the text box. Because the parent labels of different products are the same, they are the first < tr > tag, so we put the ID of the product in the < tr > label Why should I put the lang attribute in the label? Because the lang attribute is not used, it is used to define the language, and it is not easy to conflict with other attributes using lang attribute. In this way, we can obtain the ID of the product through $(this). Parents (“tr: first”). Attr (“Lang”); to obtain the product ID.

Next, start sending the Ajax request, which is sent in the post mode. There are four parameters in the post method:

The first parameter is the action to send to

The second parameter is the parameter to be passed in JSON format

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

The fourth way is to specify what type of data to receive. JSON means to receive JSON data and text means to receive stream

The total returned from the background is the total price of all goods. Therefore, in function, we first get the element of subtotal of all goods according to the ID, and then assign it to total. Totalall is the total price with freight, and the following tofixes (2) means that two decimal places are reserved. Then we get the elements of the subtotal of a single product and calculate the subtotal of a single product. In this way, the foreground page updates the part we want to update without reloading. This is where AJAX is powerful. Like easyUI before, easyUI is also an Ajax request.

Well, here’s the description of Ajax. The following is the background processing of the request just made, which is for your own project and used to record the progress of the project.

3. Background update

The action just requested by AJAX is the updatesorder() method in sortedaction, so we go to sorteraction to complete the updatesorder() method

public class SorderAction extends BaseAction<Sorder> {
public String addSorder() {
//Omit irrelevant code
//Update item quantity according to item number
public String updateSorder() {
Forder forder = (Forder) session.get("forder");
//Update shopping items, incoming product.id It is encapsulated in the model
forder = sorderService.updateSorder(model, forder);
//Calculate the new total price
session.put("forder", forder);
//Returns the new total price as a stream
inputStream = new ByteArrayInputStream(forder.getTotal().toString().getBytes());
return "stream";

The corresponding service methods are as follows:

//Sorterservice interface
public interface SorderService extends BaseService<Sorder> {
//Leave out irrelevant code
//Update item quantity according to item ID and quantity
public Forder updateSorder(Sorder sorder, Forder forder);
//Sorderserviceimpl implementation class
public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements
SorderService {
//Omit irrelevant code
public Forder updateSorder(Sorder sorder, Forder forder) {
for(Sorder temp : forder.getSorders()) {
if(temp.getProduct().getId().equals(sorder.getProduct().getId())) {
return forder;

last struts.xml The configuration in the file is to configure “stream” in < global result >, as shown below

<! -- omit other public configuration -- >
<result name="stream" type="stream">
<param name="inputName">inputStream</param>

Well, now the total price calculated in the action can be sent to the foreground in the form of flow. Ajax can receive it in its function, put it in total, and connect with the previous one.

The above is the wonderful use of Ajax technology introduced by Xiaobian. I hope it can help you. If you have any questions, please leave me a message, and I will reply you in time. Thank you very much for your support to the developeppaer website!