我通过获取请求将项目插入购物车,它有时可以正常工作,有时不在the server
上,但在localhost
上正常工作。
jquery代码
$.get("/cart/"+ id ,function(data){
$('#quantity').html(data);
});
此url命中控制器方法名为store
public function store(Request $request, $item_id) {
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($item_id);
request()->session()->put('cart', $cart);
return Session::has('cart') ? Session::get('cart')->totalQty : null;
}
这是购物车类
<?php
namespace App;
class Cart {
public $items = null;
public $totalQty = 0;
public function __construct($oldCart) {
if ($oldCart) {
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
}
}
public function add($id) {
$storedItem = ['qty' => 0, 'item' => $id];
if ($this->items) {
if (array_key_exists($id, $this->items)) {
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
//an item is added to cart along with some details
$this->items[$id] = $storedItem;
$this->totalQty++;
}
public function removeItem($id) {
$this->totalQty -= $this->items[$id]['qty'];
unset($this->items[$id]);
}
}