php - 在使用 ajax 更改输入时,仅第一行并非全部
问题描述
当我尝试更改数量然后我想据此更新总价格...使用 ajax 但只有第一行有效,所有其他行都不起作用。Ajax 请求仅适用于第一行,不适用于其他行。
购物车页面:
数据库结构:
购物车.php
<tbody>
<?php
require_once 'config.php';
$stmt = $conn->prepare("SELECT * FROM cart");
$stmt->execute();
$result = $stmt->get_result();
$sum = 0;
while($row = $result->fetch_assoc()):
?>
<tr>
<td><?= $row['id'] ?></td>
<input id="pid" type="hidden" value="<?= $row['id'] ?>">
<td><img src="<?= $row['product_image'] ?>" width="50"></td>
<td><?= $row['product_name'] ?></td>
<td>Rs. <?= number_format($row['product_price'],2) ?></td>
<input type="hidden" value="<?= $row['product_price'] ?>" id="pprice">
<td><input type="number" class="form-control" value="<?= $row['qty'] ?>" id="itemQty" style="width:75px;"></td>
<td>Rs. <?= number_format($row['total_price'],2) ?></td>
<td><a href="action.php?remove=<?= $row['id'] ?>" class="badge-danger badge">Remove</a></td>
</tr>
<?php $sum += $row['total_price']; ?>
<?php endwhile; ?>
<tr>
<td colspan="5"><b>Grand Total</b></td>
<td><b>Rs. <?= number_format($sum,2); ?></b></td>
<td><a href="#" class="btn btn-info">Checkout</a></td>
</tr>
</tbody>
ajax代码
$("#itemQty").on('change',function(){
var qty = $(this).val();
var pid = $("#pid").val();
var pprice = $("#pprice").val();
location.reload(true);
$.ajax({
url: 'action.php',
method: 'post',
cache: false,
data: {qty:qty,pid:pid,pprice:pprice},
success: function(response){
console.log(response);
}
});
});
动作.php
if(isset($_POST['qty'])){
$qty = $_POST['qty'];
$pid = $_POST['pid'];
$pprice = $_POST['pprice'];
$tprice = $qty*$pprice;
$stmt = $conn->prepare("UPDATE cart SET qty=?,total_price=? WHERE id=?");
$stmt->bind_param("iis",$qty,$tprice,$pid);
$stmt->execute();
}
解决方案
是的,因为您使用 id 并且它从第一行获取元素。您应该使用类而不是 id:
- id="pid" 由 class="pid" 更改
- id="itemQty" 更改为 class="itemQty" 等。
并从当前行中获取元素。像这样的东西:
$(".itemQty").on('change',function(){
var $el = $(this).closest('tr'); //Find parent tr element
var qty = $(this).val();
var pid = $el.find(".pid").val(); //Find element with class pid in current tr ($el)
var pprice = $el.find(".pprice").val();
$.ajax({
url: 'action.php',
method: 'post',
cache: false,
data: {qty:qty,pid:pid,pprice:pprice},
success: function(response){
console.log(response);
}
});
});
推荐阅读
- python - 使用 AWS S3 s3fs/boto3 读取 h5 文件
- php - Mysql连接三个表以获取唯一数据列表
- c# - WPF Expander 应在成员控件获得焦点时展开
- android - Android Studio 错误:无法创建项目
- java - java继承中的构造函数
- css - 在基于子域的角度应用程序上加载 css
- azure - 如何检查 Windows Server 2008 上的升级准备情况
- angular - Angular 6,AGM 在谷歌自动完成中选择第一个地址
- c++ - 错误:在执行“R CMD INSTALL”时,“结果”没有命名类型
- windows - JavaFX 将节点/对象拖到 Windows 桌面