[英]How to work with custom shopping cart in php
我已經成功建立了購物車,並且一切正常。 這是我要完成的工作:
我的問題如下: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進行調用。
一個簡單的版本可能如下所示:
// 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>
。 這將使它更具語義,因為按鈕是單擊即可執行的事情,而錨點是指向另一個頁面的鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.