内容长度:json响应Symfony2中为0 [英] Content length: 0 in a json response Symfony2
问题描述
总是空白,我在控制器中有一个动作,像这样
Always i get a blank, i have a 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);
}
在我拥有的process.json.twig文件中
in my process.json.twig file i have
{% set res = { 'data': data } %}
{{ res | json_enconde | raw }}
其他形式
{{ { 'data': data } | json_enconde | raw }}
我也尝试过这种方法:
{{ 'hello' | json_encode | raw }}
在Chrome浏览器中,我收到以下答复:
in chrome i get this response:
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 cant solve this
推荐答案
有两种方法可以实现此目标,这取决于您更喜欢哪个,以及您的操作是否应该支持多种_format
类型.
There are two ways to achieve this, it depends on which you prefer and whether or not your action is supposed to support multiple _format
types.
选项A-仅返回JSON的操作
您可以完全绕过模板.
在您的控制器中,删除@Template
批注,而改为return new Response(json_encode($process_data));
In your controller remove the @Template
annotation and instead return new Response(json_encode($process_data));
选项B-一种支持不同格式的操作,或者您只希望在模板中呈现JSON
通过呈现不同格式的动作,我指的是具有路线的动作:
By an action that renders different formats I refer to an action with a route as so:
@Route("/check/{key}.{_format}", defaults={"_format"="json"}
@Template
尽管此问题中的控制器遵循仅支持JSON但您希望在模板中呈现的动作"的路径.
Although a controller in this question goes down the route of "an action that only supports JSON but you want to render it in a template".
假设控制器的processAction
根据问题要求返回return array('data' => $process_data);
,然后将其渲染为JSON并在名为process.json.twig
的模板中进行,请按照以下说明进行操作{{ data|json_encode }}
,无需进行预处理data
或将其转换为另一个数组或模板中的类似内容.
Assuming the controller's processAction
returns return array('data' => $process_data);
as the question asks then rendering this as JSON inside a template called process.json.twig
should be done as follows {{ data|json_encode }}
, there is no need to pre-process data
or turn it into another array or anything like that inside the template.
这篇关于内容长度:json响应Symfony2中为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!