如何获得购物车数量计数不需要页面重新加载或不同的页面计数

How to get shopping cart quantity count to not require page reload or different page to count

本文关键字:加载 购物车 何获得 不需要 新加载      更新时间:2023-09-26

我有下面的代码,它给了我一个购物车中有多少商品的实时计数。问题是,它并不是那么鲜活。我必须重新加载页面或转到另一个页面才能显示。

我的方法是下面的代码是在一个名为loadProducts.php的页面。在每个页面上,我都使用所需的函数来加载它。

//Shopping Cart Quantity Count
    if(isset($_SESSION['shopping_cart']) && is_array($_SESSION['shopping_cart'])) {
    $totalquantity = 0;
    foreach($_SESSION['shopping_cart'] AS $product) {
        $totalquantity = $totalquantity + $product['quantity'];
    }
   }

 else {
       $totalquantity = 0;
  }

我不太了解Ajax,但我认为这可能是唯一的选择。

与会话一起运行有关系吗?我怎样才能在每个页面上显示一个活动元素,这样当我点击添加到购物车时,它就会发生?

假设您熟悉jQuery,您可以使用以下jQuery ajax调用:

$("#yourFormId").submit(function(){ // or if you have link use click function
    var jqxhr = $.ajax({
        method: "POST", // or GET
        url: "Your PHP to find count", 
        data: // any request param you want to send to your PHP
    })
    .done(function(content) {
        // display the count
    })
    .fail( function(xhr, textStatus) {
        // display the error
    })
    .always(function() {
    });

});

您需要再添加一行来更新显示购物车编号的DOM元素。

例如,如果您的购物车元素如下:

<button class="shopping-cart">Shopping cart (<span class="cart-item-count">0</span>)</button>

然后你只需要更新它:

$('.cart-item-count').text($totalquantity);

在javascript代码的成功响应中,您发送了一个将产品添加到购物车的请求。您必须使用ajax请求已经在您的页面中添加产品到购物车,因为如果不是这种情况,您将提交一个页面已经重新加载,因此计数已经更新。