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

时间:2015-06-01 19:25:50

标签: javascript php jquery html ajax

我有以下代码,可以直接显示购物车中有多少商品。问题是,它不是那么活。我必须重新加载页面或转到另一个页面才能显示。

我的方式是以下代码在一个名为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,但我认为这可能是唯一的选择。

这是用会话运行的吗?我怎么能在每个页面上显示这个的实时元素,所以当我点击添加到购物车时,它恰好发生了?

2 个答案:

答案 0 :(得分:0)

假设您熟悉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() {

    });


});

答案 1 :(得分:0)

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

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

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

然后你只需要用:

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

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