Content length: 0 in json symfony2 response

I always get empty, I have an action in my controller like this

/** * @Route("/check/{key}.json", defaults={"_format"="json"}) * @Template() */ public function processAction($upload_key) { /* make thing */ return array('data' => $process_data); } 

in my process.json.twig file i have

 {% set res = { 'data': data } %} {{ res | json_enconde | raw }} 

another form

 {{ { 'data': data } | json_enconde | raw }} 

I will try too:

 {{ 'hello' | json_encode | raw }} 

in chrome i get this answer:

 Connection:close Content-Length:0 Content-Type:application/json Date:Mon, 19 Dec 2011 05:13:17 GMT Server:Apache/2.2.20 (Ubuntu) X-Powered-By:PHP/5.3.6-13ubuntu3.3 

and get nothing from the server, I can not solve this problem

+4
source share
1 answer

There are two ways to achieve this, it depends on what you prefer and whether your action should support multiple _format types.

Option A is an action that returns JSON

You can completely bypass the template.

In your controller, remove the @Template annotation and instead return new Response(json_encode($process_data));

Option B is an action that supports different formats, or you just want to display JSON in the template

As a result of an action that displays different formats, I refer to an action with this route:

 @Route("/check/{key}.{_format}", defaults={"_format"="json"} @Template 

Although the controller in this matter follows the path of "an action that only supports JSON, but you want to display it in the template."

Assuming the controller processAction returns a return array('data' => $process_data); , since the question asks how to do this, since the JSON inside the template named process.json.twig should run as follows {{ data|json_encode }} , there is no need to pre-process the data or turn it into another array or something similar inside the template .

+5
source

Source: https://habr.com/ru/post/1386988/


All Articles