【发布时间】:2019-10-16 17:58:41
【问题描述】:
数据已删除数据库但表行未删除且总数未减少 php ajax 我正在为我最后一年的项目创建一个电子商务网站。我遇到了删除产品的问题。如果我删除产品已从数据库中删除成功。但最终的总数并没有减少,表格行也没有删除我到目前为止所尝试的内容,我附在下面以及下面的屏幕截图。
表格
<div class="container">
<table class="table table-striped" id="mytable">
<thead>
<tr>
<th>ProductID</th>
<th>Productname</th>
<th>Price</th>
<th>Qty</th>
<th>Amount</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div style='text-align: right; margin:10px'>
<label><h3>Total amount: </h3></label>
<span style="font-size: 40px; color: #ff0911" id='total-amount'></span>
</div>
展示产品
<script>
getProducts();
function getProducts() {
$.ajax({
type: 'GET',
url: 'all_cart.php',
dataType: 'JSON',
success: function(data) {
data.forEach(function(element) {
var id = element.id;
var product_name = element.product_name;
var price = element.price;
$('#mytable tbody').after
(
'<tr> ' +
'<td>' + id + '</td>' +
'<td>' + product_name + '</td>' +
'<td>' + price + '</td>' +
"<input type='hidden' class='price' name='price' value='" + price + "'>" +
'<td>' + "<input type = 'text' class='qty' name='qty' value='1'/>" + '</td>' +
'<td>' + "<input type = 'text' class='amount' id='amount' disabled/>" + '</td>' +
'<td>' + " <Button type='button' class='btn btn-primary' onclick='deleteProduct(this," + id + ")' >Delete</Button> " + '</td>' +
'</tr>');
});
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
计算总数
$(function() {
$(".price, .qty").on("keydown keyup click", function () {
var price = $(this).parents('tr').find('.price');
var qty= $(this).parents('tr').find('.qty');
var sum = (
Number($(price).val()) * Number($(qty).val())
);
$(this).parents('tr').find('.amount').val(sum);
calculateAmount();
});
});
function calculateAmount() {
var total = 0;
$('.amount').each(function(e){
total += Number($(this).val());
});
$('#total-amount').text(total);
}
删除产品功能
function deleteProduct(event, id) {
$.ajax({
type: 'POST',
url: 'remove.php',
dataType: 'JSON',
data: {id: id},
success: function (data) {
$(event).parent('tr').remove();
calculateAmount();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
remove.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include "db.php";
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("delete from cart where id=?");
$stmt->bind_param("s", $id);
$id = $_POST["id"];
if ($stmt->execute())
{
echo 1;
}
else
{
echo 0;
}
$stmt->close();
}
?>
【问题讨论】:
-
代替
$(event).parent('tr').remove();试试$(event).parent().parent().remove();