2021年1月

css样式:

<div style="position: relative;">
<icon>icon</icon>
<span class="cart_quantity"></span>
</div>
<style type="text/css">
        .cart_quantity{
            text-align: center;
            background-color: red;
            border-radius: 50%;
            height: 15px;
            width: 15px;
            color: white;
            position: absolute;
            z-index: 2;
            left: 20px;
            top: 0px;
        }
</style>

Jquery ajax方法:

<script type="text/javascript">
        $(function(){
            $.ajax({//更新購物車icon數量狀態
                url:"index.php?route=journal2/menu/getCartQuantity",
                type:"post",
                dataType:"json",
                success:function(json){
                    if(json.quantity > 0){
                        $(".cart_quantity").empty();
                        $(".cart_quantity").append(json.quantity);
                        $(".cart_quantity").css("display","block");
                    }else{
                        $(".cart_quantity").empty();
                        $(".cart_quantity").css("display","none");
                    }
                    
                },
                error:function(){
                    console.log("getCartQuantity Error");
                }
            });
        });
    </script>

ajax调用的php的方法:

public function getCartQuantity(){
        $query = $this->db->query("SELECT COUNT(*) as total FROM cart WHERE customer_id='".$customer_id."' ");

        $json = array();

        $json = array(
            'quantity'=> $query->row['total']
        );exit(json_encode($json));
    }

后台php写好方法,前端jq ajax调用,再把返回的数据添加到购物车icon旁边显示