0%

[技能檢定]題組四 步驟20 製作前台購物車商品列表

  1. 接著把 $_SESSION['cart'] 中所存的商品資訊列出來
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    //判斷購物車是否為空
    if(empty($_SESSION['cart'])){
    //如果為空則顯示訊息
    echo "<h3 class='ct'>目前購物車是空的</h3>";
    }else{
    ?>
    <table class="all">
    <tr>
    <td class="tt ct">編號</td>
    <td class="tt ct">商品名稱</td>
    <td class="tt ct">數量</td>
    <td class="tt ct">庫存量</td>
    <td class="tt ct">單價</td>
    <td class="tt ct">小計</td>
    <td class="tt ct">刪除</td>
    </tr>
    <?php
    //以迴圈取出購物車內容
    foreach($_SESSION['cart'] as $id => $qt){
    //取得商品資料
    $goods=$Goods->find($id);
    ?>
    <tr>
    <td class="pp"><?=$goods['no'];?></td>
    <td class="pp"><?=$goods['name'];?></td>
    <td class="pp"><?=$qt;?></td>
    <td class="pp"><?=$goods['stock'];?></td>
    <td class="pp"><?=$goods['price'];?></td>
    <td class="pp"><?=$goods['price'] * $qt;?></td>
    <td class="pp">
    <img src="./icon/0415.jpg" onclick="removeItem(<?=$id;?>)">
    </td>
    </tr>
    <?php } ?>
    </table>
    <div class="ct">
    <img src="./icon/0411.jpg" onclick="location.href='index.php'">
    <img src="./icon/0412.jpg" onclick="location.href='?do=checkout'">
    </div>
    <?php } ?>

  1. 在建立購物商品列表時,使用內建的css 樣式.all時會發現表格的大小超出版面範圍,這時可以去css檔案調整一下內距和右側區塊的大小,讓畫面可以容納更多的內容。
    /css/css.css

    1
    2
    3
    4
    5
    .all td
    {
    min-width:50px;
    padding:10px;
    }
  2. 雖然參考畫面中的購物車列表把商品數量以input的欄位來顯示,但題目中並沒有說明這個input欄位是否有其它的功能,比如改變數量時,小計欄位也會跟著改變,為了減少不必要的爭議,這邊我是使用直接顯示的方式來處理,如果要改變數量的話,可以回到商品詳細內容去重新填入數量即可。

  3. 刪除購物車商品的功能我們使用ajax的方式建立一個 removeItem(id) 函式,將要刪除的商品id傳到後台api去,然後由api來刪除session中的商品內容,完成後再使用 location.href='?do=buycart 來重新載入頁面同時清除網址帶的商品參數,藉此達成題目要求的功能

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //刪除購物車內容的函式    
    function removeItem(id){

    //透過ajax將商品id送到api/del_item.php中刪除購物車內容
    $.post("./api/del_item.php,{id}",function(){

    //重新導向至購物車頁面,清空網址列中的id與qt
    location.href='index.php?do=buycart';
    })
    }
  4. 建立 ./api/del_cart.php的檔案,並撰寫刪除購物車商品的功能。

    1
    2
    3
    4
    include_once "db.php";

    //刪除購物車內容
    unset($_SESSION['cart'][$_POST['id']]);