laravel5在ajax调用上设置cookie

时间:2016-01-08 23:43:30

标签: ajax laravel cookies

当用户点击添加到购物车时,我会创建一个新购物车并将产品添加到用户的Cookie中。但是如何在ajax响应上设置cookie。我在尝试:

//set the values for the view make
$cartId = 'someval i set earlyer'
$cookie = Cookie::forever('cartid', $cartId);

$currentCart = Cart::findOrFail($cartId);

$items = CartItem::where('cart_id','=',$currentCart->id)->get();

//this function also check the $request on a valid cookie
$total = $this->calculateCartTotal($request);
return Response::json(View::make('front.cart.render',compact('items', 'total'))->withCookie($cookie)->render());

但是值永远不会设置,我尝试刷新页面,但仍然没有cartid的cookie。如何为ajax响应设置cookie

1 个答案:

答案 0 :(得分:1)

试试这个:

return Response::json(
    View::make('front.cart.render',compact('items', 'total'))->render()
)->withCookie($cookie);

rendor属于View

withCookie属于Response

检查响应标头。

Set-Cookie:cartid=...