我有一个JSON端点,用于将产品添加到购物车中。它检查购物车是否已经存在。如果不存在,则创建一个购物车,购物车Id存储在cookie中。那么我该如何将cookie附加到symfony2的JsonResponse?
在非ajax版本中,如果我从我的操作中呈现模板,我可以使用:
$response = new Response();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));
$this->render('<template_path>', '<array_options>', $response);
请帮助我如何为JsonResponse做这件事。
在我看来,你会在以下链接中找到答案:
如何在symfony2控制器中发送json响应
http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/JsonResponse.html
http://symfony.com/doc/current/components/http_foundation/introduction.html
最好的方法,看看链接和学习,但如果你找不到答案,也许这将是好的:
use Symfony'Component'HttpFoundation'Response;
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));
return $response;
还有一个有用的JsonResponse类,它可以让这变得更容易:
use Symfony'Component'HttpFoundation'JsonResponse;
$response = new JsonResponse();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));
return $response;
我希望,这将是有益的:)