[英]How to attach cookies to JSON Response in symfony2?
I have JSON endpoint which is used to add product to cart. 我有JSON端点,用于将产品添加到购物车。 It checks whether the cart already exists or no. 它会检查购物车是否已存在或没有。 If not then it creates a cart and the cart Id is stored in cookie. 如果没有,则创建购物车,购物车ID存储在cookie中。 So I how do I attach cookie to the symfony2's JsonResponse ? 所以我如何将cookie附加到symfony2的JsonResponse?
In a non ajax version if I am rendering a template from my action I can use: 在非ajax版本中,如果我从我的动作渲染模板,我可以使用:
$response = new Response();
$response->headers->setCookie(new Cookie(‘cookie_name’, ‘cookie_value’));
$this->render('<template_path>', '<array_options>', $response);
Please help me on how to do it for a JsonResponse. 请帮我介绍如何为JsonResponse做这件事。
In my opinion, you will find the answer under the following links: 在我看来,您将在以下链接中找到答案:
How can i send json response in symfony2 controller 如何在symfony2控制器中发送json响应
http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/JsonResponse.html http://api.symfony.com/2.2/Symfony/Component/HttpFoundation/JsonResponse.html
http://symfony.com/doc/current/components/http_foundation/introduction.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;
There is also a helpful JsonResponse class, which can make this even easier: 还有一个有用的JsonResponse类,它可以使这更容易:
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 :) 我希望,这将有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.