如何在symfony2中将cookie附加到JSON响应? [英] How to attach cookies to JSON Response in symfony2?
问题描述
我有JSON端点,用于将产品添加到购物车.它检查购物车是否已经存在.如果没有,它将创建一个购物车并将购物车ID存储在cookie中.因此,我如何将cookie附加到symfony2的JsonResponse上?
I have JSON endpoint which is used to add product to cart. It checks whether the cart already exists or no. If not then it creates a cart and the cart Id is stored in cookie. So I how do I attach cookie to the symfony2's JsonResponse ?
在非ajax版本中,如果我要从动作中渲染模板,则可以使用:
In a non ajax version if I am rendering a template from my action I can use:
$response = new Response();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));
$this->render('<template_path>', '<array_options>', $response);
请帮助我了解如何针对JsonResponse进行操作.
Please help me on how to do it for a JsonResponse.
推荐答案
我认为,您会在以下链接下找到答案:
In my opinion, you will find the answer under the following links:
http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/JsonResponse.html
http://symfony.com/doc/current/components/http_foundation/introduction.html
查看链接和学习的最佳方法,但是如果找不到答案,也许会很好:
The best way, to see links and learn, but if you will not find the answer, maybe this will be good:
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类,它可以使这变得更加容易:
There is also a helpful JsonResponse class, which can make this even easier:
use Symfony\Component\HttpFoundation\JsonResponse;
$response = new JsonResponse();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));
return $response;
我希望这会有所帮助:)
I hope, this will be helpfull :)
这篇关于如何在symfony2中将cookie附加到JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!