2017-08-10 28 views
-3

我正在尋找顯示類似於購物車的數字。我被給了php代碼,它現在顯示一個cookie值,它的作品種類可以接受,如果你點擊添加到購物車,並且在你輸入的內容中有錯誤,它會向cookie添加1,但不會添加任何東西到購物車。拆分項目數量,類似於購物車

我嘗試使用AngularJS來顯示會話變量的工作稍微好一些,但它不會更新,直到您刷新頁面。

任何人都可以指出我正確的方向,所以我可以嘗試找出自己。

這是我orginally給出的代碼:

if (!isset($_COOKIE['count'])) 
{ 
    $cookie = 0; 
    setcookie("count", $cookie); 
} 
else 
{ 

    if (isset($_GET["add"])) 
     { 
     $cookie = ++$_COOKIE['count']; 
     setcookie("count",$cookie); 
     } 
    else if (isset($_GET["remove"])) 
     { 
     $cookie = --$_COOKIE['count']; 
     setcookie("count", $cookie); 
     } 
    else { 
     $cookie = $_COOKIE['count']; 
     setcookie("count", $cookie); 
     } 

    $cookie = $_COOKIE['count']; 

    if ($cookie <= 0) 
    { 
     $cookie = 0; 
     setcookie("count", $cookie); 
    } 
} 

它再印像這樣

<li><a><div ng-app="" class="circle"> <?php echo $cookie ?></div></a></li> 

我試圖換款回波$ cookie來呼應會話陣列長度和使用也嘗試

<li><a><div ng-app="" class="circle">{{ <?php echo count($_SESSION['certificates']) ?>}}</div></a></li> 

我也試過此鏈接:https://codepen.io/anon/pen/mMwVPb

但並不完全理解這一切,並不能讓它在我的網頁上工作。

它幾乎按我希望的方式工作,但我只需刷新頁面以顯示會話數組長度。如果有一種方法可以顯示會話的值,而不必刷新頁面,我認爲這可以解決它。

+0

你能後你試過的代碼? – Vivz

+2

由於您沒有提供任何代碼,因此無法爲您提供幫助。 – epascarello

+0

更新了問題 – Theory

回答

0

我不會惹一塊餅乾,除非你想在用戶離開你的網站時留下購物車,然後再回到你的商店。此時,您可以將購物車中的商品存儲在數據庫中,或者將某個商品的參考ID存儲到cookie或其他內容中。人們可以關閉cookies,因此如果您的購物車取決於Cookie並且用戶將其關閉,那麼您就是SOL。

我想你的車在會話中儲存,因爲你可以在會話中輕鬆存儲陣列:

# Simple example of add to cart function 
addToCart($sku,$qty=1) 
    { 
     # Make sure the quantity is a number 
     if(!is_numeric($qty)) 
      $qty = 1; 
     # If the cart is not yet set, create it 
     if(!isset($_SESSION['cart'])) 
      $_SESSION['cart'] = array(); 
     # If the item is already in the cart, increment the quantity 
     if(isset($_SESSION['cart'][$sku])) 
      $_SESSION['cart'][$sku] += $qty; 
     # If not in the cart already, create it 
     else 
      $_SESSION['cart'][$sku] = $qty; 
    } 

# Remember to start session on every page 
session_start(); 

# To add to cart 
if(isset($_REQUEST['add'])) { 
    # Insert the sku in param 1, quantity into param 2 
    addToCart($_REQUEST['ITEMCODE'],$_REQUEST['QTY']); 
} 
# Set some storage variables 
$totalQty = 
$itemsQty = 0; 
# To get qty in cart 
if(!empty($_SESSION['cart'])) { 
    # Loop through items in cart 
    foreach($_SESSION['cart'] as $sku => $qty) { 
     $totalQty += $qty; 
     $itemsQty += 1; 
    } 
} 
?> 
<!-- If you have 5 products in the cart, this will say 5 --> 
<h2>Total products in cart: <?php echo $itemsQty ?></h2> 
<!-- If you have 5 products with quantity of 2 per product, this will write 10 --> 
<h2>Total items in cart: <?php echo $totalQty ?></h2> 
+0

所以我使用了這個會話,它幾乎按我想要的方式工作。購物車編號顯示在標題中,並且始終位於實際編號後面1,所以如果是2個項目,它將顯示1。 – Theory

+0

如果將商品添加到購物車,並且在刷新頁面之前它不註冊,則只需執行在添加購物車後重新定向標題, – Rasclatt