我已经成功建造了一个购物车,一切正常。这是我想完成的:
- 如果用户单击"添加到购物车"按钮,则应将其添加到购物车中,并在添加的项目更新中刷新同一页面。
- 如果用户单击图像或查看按钮,它将显示项目的图像。
我的问题如下: 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,该JavaScript将使用众多不同的方式之一使用Ajax。P>
一个简单的版本看起来像这样:
// 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>
。这将使它更加语义,因为按钮是单击要做的事情,而锚是另一个页面的链接。