我有购物车,我通过AJAX(fetch)添加项目。当我将项目添加到购物车并在调试工具栏中检查请求时,会话已正确设置。但页面重新加载后,会话消失。这很奇怪,因为当我使用相同的代码将项目添加到购物车而不是通过AJAX(使用链接和重定向)时,一切正常。哪里可能有问题?
public function addItem(int $id, string $type, int $quantity = 1)
{
$item = new CartItem();
$item->setId($id);
$item->setQuantity($quantity);
$item->setType($type);
$this->items[] = $item;
$this->session->set(self::SHOPPING_CART_SESSION_NAME, $this->items);
}
/**
* @Route("/add-to-cart", name="add_item_to_cart")
*/
public function addItemToCart(Request $request)
{
$data = json_decode($request->getContent());
$type = $data->type;
$id = intval($data->id);
$quantity = intval($data->quantity);
$this->shoppingCartService->addItemToShoppingCart($id, $type, $quantity);
return new JsonResponse('success', 200);
}
fetch('/add-to-cart', {
method: 'post',
body: JSON.stringify({
type: type,
id: productId,
quantity: quantity
})
}).then((response) => {
response.json().then(data => {
console.log(data);
});
}).catch((error) => {
});