问题
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 ?
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);
Please help me on how to do it for a JsonResponse.
回答1:
In my opinion, you will find the answer under the following links:
How can i send json response in symfony2 controller
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;
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 :)
来源:https://stackoverflow.com/questions/20626099/how-to-attach-cookies-to-json-response-in-symfony2