如何在不刷新页面的情况下执行删除购物车和更新购物车



我有一个简单的代码来添加商品到购物车,当用户删除商品到购物车时,页面刷新并使其滚动回顶部。更新量也是如此。我相信我可以有这些功能的工作没有页面刷新,但我不知道如何执行这一点。这是购物车代码

<?php 
session_start();
// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
$delete_id = (int)$_GET['delete_id'];
// search for the product to delete
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $delete_id) {
unset($_SESSION['cart'][$key]);
}
}
}
// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
$update_id = (int)$_GET['update_id'];
$quantity = (int)$_GET['quantity'];
// search for the product to update
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $update_id) {
if(isset($product['quantity'])) {
$_SESSION['cart'][$key]['quantity'] = $quantity;
} else {
$_SESSION['cart'][$key]['quantity'] = 1;
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cart</title>
</head>
<body>
<!-- Header menu with logo, about us, and cart menu -->
<div id="header">
<div id="logo">Logo</div>
<div id="test">
<a href="test.php">products Page</a>
</div>
<div id="about-us">About Us</div>
<div id="cart-menu">      
<a href="cart.php">Cart (<?=count($_SESSION['cart'])?>)</a>
</div>
</div>
<!-- Cart list -->
<div id="cart-list">
<?php 
if (empty($_SESSION['cart'])) {
echo '<p>Your cart is empty</p>';
} else {
$total = 0;
foreach($_SESSION['cart'] as $product) {
echo $product['name']. " <br>";
echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';            
$subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal">'.number_format($subtotal,2).'</span></p>';
$total += $subtotal;
echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
echo '<hr>';
}
echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
}
?>
</div>
<script>
function incrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
var newQuantity = currentQuantity + 1;
updateQuantity(id, newQuantity);
}
function decrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
if(currentQuantity > 1) {
var newQuantity = currentQuantity - 1;
updateQuantity(id, newQuantity);
}
}
function updateQuantity(id, value) {
var url = "cart.php?update_id=" + id + "&quantity=" + value;
// Change the displayed quantity
document.getElementById('product-' + id + '-quantity').innerHTML = value;
// Update the subtotal
var price = parseFloat(document.getElementById('product-' + id + '-subtotal').innerHTML) / parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
document.getElementById('product-' + id + '-subtotal').innerHTML = price * value;
updateTotal();
window.location.href = url;
}
function removeFromCart(id) {
var url = "cart.php?delete_id=" + id;
window.location.href = url;
}
function updateTotal() {
var total = 0;
var subtotals = document.getElementsByClassName('product-subtotal');
for (var i = 0; i < subtotals.length; i++) {
total += parseFloat(subtotals[i].innerHTML);
}
document.getElementById('total').innerHTML = total;
}
</script>
</body>
</html>

我读到的是我应该添加事件监听器到按钮和使用$.ajax()方法…我不太擅长编码,所以我不能实现这个,所以我甚至不知道它是否会工作

<?php 
session_start();
// check if the delete_id is passed via the URL
if(isset($_GET['delete_id'])) {
$delete_id = (int)$_GET['delete_id'];
// search for the product to delete
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $delete_id) {
unset($_SESSION['cart'][$key]);
echo "success";die;
}
}
}
// check if the update_id and quantity are passed via the URL
if(isset($_GET['update_id']) && isset($_GET['quantity'])) {
$update_id = (int)$_GET['update_id'];
$quantity = (int)$_GET['quantity'];
// search for the product to update
foreach($_SESSION['cart'] as $key => $product) {
if($product['id'] === $update_id) {
if(isset($product['quantity'])) {
$_SESSION['cart'][$key]['quantity'] = $quantity;
} else {
$_SESSION['cart'][$key]['quantity'] = 1;
}
echo "success";die;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
<div id="header">
<div id="logo">Logo</div>
<div id="test">
<a href="test.php">products Page</a>
</div>
<div id="about-us">About Us</div>
<div id="cart-menu">      
<a href="cart.php">Cart (<?=count($_SESSION['cart'])?>)</a>
</div>
</div>
<!-- Cart list -->
<div id="cart-list">
<?php 
if (empty($_SESSION['cart'])) {
echo '<p>Your cart is empty</p>';
} else {
$total = 0;
foreach($_SESSION['cart'] as $product) {
echo "<div class='product product-".$product['id']."'>";
echo $product['name']. " <br>";
echo '<input type="hidden" id="product-'.$product['id'].'-price" value="'.$product['price'].'">';
echo '<button type="button" onclick="decrementQuantity('.$product['id'].')">-</button>';
echo '<span id="product-'.$product['id'].'-quantity">'.(isset($product['quantity']) ? $product['quantity'] : 1).'</span>';
echo '<button type="button" onclick="incrementQuantity('.$product['id'].')">+</button>';            
$subtotal = $product['price'] * (isset($product['quantity']) ? $product['quantity'] : 1);
echo '<p>Subtotal: $<span id="product-'.$product['id'].'-subtotal" class="subtotals">'.number_format($subtotal,2).'</span></p>';
$total += $subtotal;
echo '<p><button type="button" onclick="removeFromCart('.$product['id'].')">Remove Item from Cart</button></p>';
echo '<hr></div>';
}
echo '<p>Total: $<span id="total">'.number_format($total,2).'</span></p>';
}
?>
</div>
<script>
function incrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
var newQuantity = currentQuantity + 1;
updateQuantity(id, newQuantity);
}
function decrementQuantity(id) {
var currentQuantity = parseInt(document.getElementById('product-' + id + '-quantity').innerHTML);
if(currentQuantity > 1) {
var newQuantity = currentQuantity - 1;
updateQuantity(id, newQuantity);
}
}
function updateQuantity(id, value) {
var $proC = $('.product.product-' + id );
var product_price = $('#product-'+id+'-price').val();

$proC.find('button').attr("disabled","disabled");
var url = "cart.php?update_id=" + id + "&quantity=" + value;

$.ajax({
url:url,
type:'GET',
success:function(response){
$proC.find('button').removeAttr("disabled");
if($.trim(response) == 'success'){
document.getElementById('product-'+id+'-quantity').innerHTML = value;
document.getElementById('product-'+id+'-subtotal').innerHTML = product_price * value;
}else{
alert("Something went wrong.try again..");
}
updateTotal();
},
error:function(err){
$proC.find('button').removeAttr("disabled");
alert(err);
}
})
}
function removeFromCart(id) {
var url = "cart.php?delete_id=" + id;
$.ajax({
url:url,
type:'GET',
success:function(response){
if($.trim(response) == 'success'){
$('.product.product-'+id).remove();
alert("Product removed.");
}else{
alert("Something went wrong.try again..");
}
},
error:function(err){
alert(err);
}
})
}
function updateTotal() {
var total = 0;
var subtotals = document.getElementsByClassName('subtotals');
for (var i = 0; i < subtotals.length; i++) {
total += parseFloat(subtotals[i].innerHTML);
}
document.getElementById('total').innerHTML = total;
}
</script>
</body>
</html>

最新更新