Home Web Front-end JS Tutorial Example code of using Ajax technology to partially refresh product quantity and total price

Example code of using Ajax technology to partially refresh product quantity and total price

May 23, 2018 pm 05:32 PM
ajax accomplish local

This article mainly introduces you to the example code of using Ajax technology to partially refresh the quantity and total price of goods. It is very good. Friends who need it can take a look.

1. Question Analysis

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

Example code of using Ajax technology to partially refresh product quantity and total price

The functions are as above. Before Ajax, it was usually modified according to the user. Find the Action for the value, and then return to the new jsp page to reload the entire page to complete the update of the numbers. 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 above picture:

<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="/static/imghw/default1.png"  data-src="${shop}/files/${sorder.product.pic}"  class="lazy"      style="max-width:90%"  style="max-width:90%" / alt="Example code of using Ajax technology to partially refresh product quantity and total price" ></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 looks like a lot, but the function is actually very simple. It just takes out the corresponding data from the domain and displays it. We now need to implement the above description As for the function, let’s analyze the idea first:

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

In this event, we get the user input number, to determine the legality of the input, because it is necessary to prevent users from arbitrarily inputting;

If it is legal, the data will be sent to the background through an Ajax request;

The background will call the corresponding business for the new quantity The logical method gets the new result and returns it to the front desk through the stream;

After Ajax receives the result, it updates the data at the corresponding location. 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 be positioned Go to this text box, which is located through the class selector. Because it is a text box, use change() to 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 This is used 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 that 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 the json format

The third parameter is a function (result), and the result is used to receive the background transmission Overcoming data

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

The total returned from the background is the total price of all goods, so In the function, first we get the elements of the subtotal of all products based on the ID and then assign the value to total. totalAll is the total price plus shipping cost, and the latter toFixes(2) means keeping two decimal places. Then get the element of the subtotal of a single product and calculate the subtotal of a single product, so that the front page updates the part we want to update without reloading. This is the power of Ajax. This and the previous Like EasyUI, EasyUI is also an Ajax request.

Okay, that’s all the introduction to the Ajax part. The following is the background processing of the request just now, which is for my own project and is used to record the progress of the project.

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中了,跟前面的就接上了。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

完美解决ajax访问遇到Session失效的问题

ajax内部值外部调用不了的原因及解决方法

全面解析Ajax综合应用

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

How to implement exact division operation in Golang How to implement exact division operation in Golang Feb 20, 2024 pm 10:51 PM

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

See all articles