Home > Web Front-end > JS Tutorial > How to partially refresh product quantity and total price with Ajax

How to partially refresh product quantity and total price with Ajax

php中世界最好的语言
Release: 2018-04-04 14:41:30
Original
1691 people have browsed it

This time I will show you how to partially refresh the quantity and total price of goods with Ajax. What are the precautions for Ajax to partially refresh the quantity and total price of goods. The following is a practical case. Let’s take a look. .

1. Analysis of the problem

First, take a look at the situation on the page:

How to partially refresh product quantity and total price with Ajax

The function is as above. Before Ajax, the Action was usually found based on the value modified by the user, and then the new jsp page was returned to reload the entire page to complete the digital update. But with Ajax technology, we can use Ajax technology to partially refresh the place to be changed instead of reloading the entire page. First, take a look at the code of the jsp part corresponding to the picture above:


<p class="section_container">
<!-- 购物车 -->
<p id="shopping_cart">
<p class="message success">我的购物车</p>
<table class="data-table cart-table" cellpadding="0" cellspacing="0">
<tr>
<th class="align_center" width="10%">商品编号</th>
<th class="align_left" width="35%" colspan="2">商品名称</th>
<th class="align_center" width="10%">销售价格</th>
<th class="align_center" width="20%">数量</th>
<th class="align_center" width="15%">小计</th>
<th class="align_center" width="10%">删除</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"><img  src="${shop}/files/${sorder.product.pic}"    style="max-width:90%"  style="max-width:90%" / alt="How to partially refresh product quantity and total price with Ajax" ></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">
<!-- 文本框 -->
<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>
<!-- 结算 -->
<p class="totals">
<table id="totals-table">
<tbody>
<tr>
<td width="60%" colspan="1" class="align_left"><strong>小计</strong></td>
<td class="align_right" ><strong>¥<span
class="price" id="total">${sessionScope.forder.total}</span>
</strong></td>
</tr>
<tr>
<td width="60%" colspan="1" class="align_left">运费</td>
<td class="align_right" >¥<span class="price" id="yunfei">0.00</span></td>
</tr>
<tr>
<td width="60%" colspan="1" class="align_left total"><strong>总计</strong></td>
<td class="align_right" >¥<span class="total" id="totalAll"><strong>${sessionScope.forder.total}</strong></span>
</td>
</tr>
</tbody>
</table>
<p class="action_buttonbar">
<font><a href="${shop}/user/confirm.jsp">
<button type="button" title="" class="checkout fr" style="background-color: #f38256;">订单确认</button></a>
</font>
<font><a href="#">
<button type="button" title="" class=" fr">
<font>清空购物车</font>
</button>
</font>
<a href="${shop}/index.jsp">
<button type="button" title="" class="continue fr">
<font>继续购物</font>
</button></a>
<p style="clear:both"></p>
</p>
</p>
</p>
Copy after login


It seems like a lot, but in fact the function is very simple, that is It’s just to take out the corresponding data from the domain and display it. If we want to implement the function described above, let’s analyze the idea first:

First we must register an event: that is, the text box where the quantity is modified triggers Event;

In this event, we get the number entered by the user and determine the legality of the input, because we want to prevent the user from inputting randomly;

If it is legal, the data is sent to Backend;

The backend calls the corresponding business logic method to get the new result for the new quantity, and returns it to the frontend through the stream;

After Ajax receives the result, it then updates the corresponding position data is updated. The entire process is complete.

If it is illegal, the number before modification will be displayed. No processing is done

2. Implementation of Ajax request

After analyzing the process, we will start to implement it. First, js Part of the code is posted here, and then we analyze it in detail according to the above process:


<script type="text/javascript">
$(function(){
//1. 注册事件
$(".text").change(function(){
//2. 验证数据的有效性
var number = this.value; //也可以使用$(this).val();
//isNaN(number)表示若number不是数字就返回真
if(!isNaN(number) && parseInt(number)==number && number>0){ 
//如果合法,同步更新的数
$(this).attr("lang", number);
//找到当前标签中第一个是tr的父节点,然后拿到属性为lang的值,也就是商品的id
var pid = $(this).parents("tr:first").attr("lang");
//发送Ajax请求,传输当前的数量与商品的id,返回修改数量后的总价格
$.post("sorder_updateSorder.action", 
{number:number, &#39;product.id&#39;:pid},
function(total){ 
$("#total").html(total); //所有商品小计
var yunfei = $("#yunfei").html();
$("#totalAll").html((total*1 + yunfei*1).toFixed(2));//所有商品小计和运费的和
}, "text");
//计算单个商品的小计,保留两位小数
var price = ($(this).parent().prev().html()*number).toFixed(2);
$(this).parent().next().html(price);
} else {
//如果非法,还原为刚刚合法的数
this.value = $(this).attr("lang");
}
})
})
</script>
Copy after login


2.1 Registration event

We can see from the above code that the registration event must first locate this text box. Here it is located through the class selector . Because it is a text box, change() is used. Register the event, and then define a function() function inside to handle the event.

2.2 Determine the legality of the data

Okay, after registering the event, we must first judge the legality of the number entered by the user, because the user may have entered 0 or a negative number, a decimal may be entered, or even letters or other characters may be entered, etc. So it needs to be verified.

isNaN(number) means that if number is not a number, it will return true. We can use this function to determine whether it is a number; parseInt(number) means to round the array and then compare it with itself , we cleverly used 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: Need What parameters are passed? First of all, if the user wants to update the quantity, there is no doubt that the number entered by the user must be passed. Secondly, which product should be passed? That is to say, we need to get the ID number of the product the user wants to modify. After knowing the parameters to be passed, we can find a way to get the ID number.

There is a problem here. The user may have more than one product in the shopping cart. It is natural to think that it would be very good if you can use one statement to get the IDs of different products. Therefore, I thought of You can use the parent tag of the text box, because different products have the same parent tag, which is the first tag, so we put the product id in the lang attribute of the tag. , why should it be placed 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 conflict with other attributes using the lang attribute~ In this way, we can pass $(this).parents("tr:first").attr( "lang"); to get the product id.

Next, start sending the Ajax request, using the post method. There are four parameters in the post method:

The first parameter is to Action

The second parameter is the parameter to be passed, using json format

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

The fourth way is to specify what type of data to receive. json means receiving json data, text means receiving stream

  从后台返回的total是所有商品的总价格,所以在function中,首先我们根据id拿到所有商品小计的元素然后赋值为total即可,totalAll是加了运费的总价,后面那个toFixes(2)表示保留两位小数。然后再拿到单个商品小计的元素,计算一下单个商品的小计,这样前台页面在没有重新载入的情况下,更新了我们想要更新的部分,这就是Ajax强大的地方,这个和前面EasyUI一样的,EasyUI也是Ajax请求。

   好了,关于Ajax部分到这里就介绍完了,下面是后台的处理刚刚的请求,是针对自己这个项目的,用来记录项目进度用的。

3. 后台的更新

  刚刚Ajax请求的action是SortedAction中的updateSorder()方法,所以我们去SorderAction中完成updateSorder()方法:


@Controller
@Scope("prototype")
public class SorderAction extends BaseAction<Sorder> {
public String addSorder() {
//省略无关的代码……
//根据商品编号更新商品数量
public String updateSorder() {
Forder forder = (Forder) session.get("forder");
//更新购物项,传进来的product.id被封装到了model中
forder = sorderService.updateSorder(model, forder);
//计算新的总价格
forder.setTotal(forderService.cluTotal(forder));
session.put("forder", forder);
//以流的形式返回新的总价格
inputStream = new ByteArrayInputStream(forder.getTotal().toString().getBytes());
return "stream";
}
}
Copy after login


相应的Service中的方法完善如下:


//SorderService接口
public interface SorderService extends BaseService<Sorder> {
//省去无关的代码……
//根据商品id和数量更新商品数量
public Forder updateSorder(Sorder sorder, Forder forder);
}
//SorderServiceImpl实现类
@Service("sorderService")
public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements
SorderService {
//省略无关的代码……
@Override
public 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;
}
}
Copy after login


最后struts.xml文件中的配置,是把”stream”配在了里面,如下


<global-results>
<!-- 省去其他公共配置 -->
<result name="stream" type="stream">
<param name="inputName">inputStream</param>
</result>
</global-results>
Copy after login

   好了,现在Action中计算出的总价格就可以通过流的形式传到前台了,Ajax就可以在它的function中接收到,放到total中了,跟前面的就接上了。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

ajax操作全局监测,用户session失效怎么处理

ajax访问到Session失效如何处理

The above is the detailed content of How to partially refresh product quantity and total price with Ajax. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template