我已经成功建立了一个购物车,一切正常。这是我想要完成的:
我的问题如下:1。如果用户点击添加到购物车按钮,它会添加但重定向到cart.php文件(这不是我想要的,我希望页面重新加载添加的项目更新)2我试过用:
$head = $_SERVER['HTTP_REFERER'];
echo '<script>location.href="'.$head.'"</script>';
exit();
当用户单击“添加到购物车”按钮时,它似乎运行良好,但是当用户单击图像或单击“查看”按钮时,它会刷新同一页面而不允许用户查看图像。
以下是我的代码。
//My custom shopping cart script
if (isset($_GET['pid'])) {
$pid = $_GET['pid'];
$wasFound = false;
$i = 0;
// If the cart session variable is not set or cart array is empty
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
// RUN IF THE CART IS EMPTY OR NOT SET
$_SESSION["cart_array"] = array(0 => array("item_id" => $pid, "quantity" => 1));
} else {
// RUN IF THE CART HAS AT LEAST ONE ITEM IN IT
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while (list($key, $value) = each($each_item)) {
if ($key == "item_id" && $value == $pid) {
// That item is in cart already so let's adjust its quantity using array_splice()
array_splice($_SESSION["cart_array"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
$wasFound = true;
} // close if condition
} // close while loop
} // close foreach loop
if ($wasFound == false) {
array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
}
}
$head = $_SERVER['HTTP_REFERER'];
//header("location: $head");
echo '<script>location.href="'.$head.'"</script>';
exit();
}?>
<!--My Products item Display-->
<div class="col-md-4">
<div class="product-img product-img-brd">
<a href="pro_single.php?pid='.$id.'"><img class="full-width img-responsive" src="../../backend/'.$product_img.'" alt="'.$product_name.'"></a>
<a class="product-review" href="pro_single.php?pid='.$id.'">Quick review</a>
<a class="add-to-cart" href="cart.php?pid='.$id.'" ><i class="fa fa-shopping-cart"></i> Add to cart </a>
<div class="product-price">
<span class="title-price">$'.$price.'</span>
</div>
</div>
而不是使它成为一个链接(使用锚标记<a>
),你会想要编写一些JavaScript,它将使用许多不同的方法之一来用AJAX调用它。
简单版本可能如下所示:
// update <a> in HTML
<a onclick="addToCart(' . $id . ')">Add to Cart</a>
// JavaScript
const addToCart = id => fetch('cart.php?pid=' + id).then(response => { /* do something with response here */ });
这是一个简单的版本,但它给你一个想法。有大量的AJAX指南与所有不同的方法(我更喜欢新的fetch()
,但也有jQuery.ajax()
和纯XMLHttpRequest
等)。
当你使用带链接的锚时,它会说“去这个地方”,这不是你想要的。使用AJAX,您可以在不影响页面本身流量的情况下下载数据。
旁注:理想情况下,将你的<a>
改为<button>
。这将使其更具语义性,因为按钮是点击做事情的东西,而锚点是指向另一个页面的链接。