在symfony中将content-type设置为json

Har*_*rup 9 json symfony1 content-type

我正在使用symfony 1.4,使用propel作为ORM创建我的项目.当我调用url时,我希望以JSON格式获得响应.我已将标题设置为"application/json",但它无法正常工作,我收到的是HTML格式的响应...我无法解码.我们如何在symfony中设置内容类型?示例代码:动作 -

 public function executeIndex(sfWebRequest $request)
 {
     $data_array=array("name" => "harry", "mobile" => "9876543210");
     $data_json=json_encode($data_array);
     $this->output=$data_json;  
 }
Run Code Online (Sandbox Code Playgroud)

视图-

<?php
  header('Content-type: application/json');
  echo $output;
?>
Run Code Online (Sandbox Code Playgroud)

Har*_*rup 20

好吧,我得到了我错的地方..你的代码应该是..行动 -

public function executeIndex(sfWebRequest $request)
{
 $this->getResponse()->setContentType('application/json');
 $data_array=array("name" => "harry", "mobile" => "9876543210");
 $data_json=json_encode($data_array);
 return $this->renderText($data_json); 
}
Run Code Online (Sandbox Code Playgroud)

这段代码对我有用,如果您有更好的解决方案,请发布...

  • 如果您使用$ this-> renderText(),则无需在视图模板中包含任何内容. (3认同)

Dan*_*his 6

您还可以在模块的view.yml(apps/{app_name}/modules/{module_name} /config/view.yml)文件中定义它.

indexSuccess:
  has_layout: false
  http_metas:
    content-type: application/json
Run Code Online (Sandbox Code Playgroud)