如何使用 ajax Laravel 8 更新总数量

How to update total quantity with ajax Laravel 8

我有我的购物车,我正在使用 ajax 添加到购物车。它有效,但我不知道如何更新位于 header 的总数量。没有用于选择数量的字段的输入,我希望它在每个按钮“添加到购物车”后增加 1(ajax)。我该怎么做?

购物车控制器:

  public function addCart(Request $request, $id){
    $product = Product::find($id);
    $oldCart = Session::has('cart') ? Session::get('cart') : NULL;
    $cart = new Cart($oldCart);
    $cart->add($product, $product->id);

    $request = Session::put('cart', $cart);

    Session::flash('add-product', $product->name);

    return redirect()->back();
  }

包含主要逻辑的自定义购物车class:

public function add($item, $id){
      $storedItem = [
        'qty' => 0,
        'id' => $item->id,
        'prod_url' => $item->url,
        'code_cat' => $item->category->code,
        'url_cat' => $item->category->url,
        'name' => $item->name,
        'cost' => $item->price,
        'price' => $item->price,
        'img' => $item->cardImage->path
      ];
      if($this->items){
        if(array_key_exists($id, $this->items)){
          $storedItem = $this->items[$id];
        }
      }
        $storedItem['qty']++;
        $storedItem['cost'] = $item->price * $storedItem['qty'];
        $this->items[$id] = $storedItem;
        $this->totalQty++;
        $this->totalPrice += $item->price;
    }

添加到购物车按钮:

<div class="product-icon-container">
  <a href="{{ route('basket-add', [ 'id' => $item->id ]) }}" class="scrollOffset btn btn-success mt-2 mb-1">Add to Cart</a>
  <a href="#" class="btn btn-danger mt-2 mb-1">Buy now!</a>
</div>

header中的总数量:

<span class="prodcount">{{ Session::has('cart') ? Session::get('cart')->totalQty : '0' }}</span><i class="fas fa-shopping-basket"></i><span class="basket-text">Cart</span>

简单ajax请求:

$(document).ready(function() {
 $('.product-icon-container').find('a.scrollOffset').click(function (event){
   event.preventDefault();
   $.ajax({
      url: $(this).attr('href')
   });
  return false;
 });
});

在你的add()方法中,你需要return更新数量的结果。

public function add($item, $id){
      // your code
    return response()->json(['success' => true]);
}

然后在你的 ajax 请求中,它有一个 success 函数来检查请求是否成功。

$.ajax({
      url: $(this).attr('href'),
    success: function (data, status, xhr) {
      // onReponseSuccess
      $('.prodcount').text(your_qty)
    },
    error: (jqXhr, textStatus, errorMessage) {
      // handle onReponseError
    }
});

我的问题已被俄语 Whosebug 的用户完全解决 at the link

作为一种选择,您可以通过稍微更改@HEL Mab 的代码来获得很好的解决方案。

$(document).ready(function() {
      $('.product-icon-container').find('a.scrollOffset').click(function (event){
        event.preventDefault();
        let totalQty = parseInt($('.prodcount').text());
        $.ajax({

        url: $(this).attr('href'),
        success: function (data, status, xhr) {
          // onReponseSuccess
          totalQty++;
          $('.prodcount').text(totalQty);
        },
        error: function(jqXhr, textStatus, errorMessage) {
          // handle onReponseError
        }
    });
  });
});