English 中文(简体)
在symfony中将内容类型设置为json
原标题:set content-type to json in symfony

I am using symfony 1.4, to create my project with propel as ORM. i want to get the response in JSON format, when i call a url. I have set the headers to "application/json" but it is not working, i am getting the response back in HTML format..which i am not able to decode. How can we set content-type in symfony?? example code: Action-

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

查看-

<?php
  header( Content-type: application/json );
  echo $output;
?>
最佳回答

ok i got where i was going wrong..yhe code should have been.. Action-

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); 
}

这个代码对我有效,如果你有更好的解决方案,请发布。。

问题回答

您也可以在模块的view.yml(apps/{app_name}/modules/{module_name}/config/view.yml)文件中对此进行定义。

indexSuccess:
  has_layout: false
  http_metas:
    content-type: application/json

哦作为一种替代方案,我只想说我一直在使用路由系统,它提供了一种非常巧妙的方法来完成这项工作:

->;在你的路线上。yml

json_test:
  url: /test
  class: sfRequestRoute
  param: { module: test, action: index, sf_format: json }

然后,框架将自动获取您必须创建的index.json.php视图。如上所述,您可以使用json_encode在操作中生成内容,尽管有一些参数可以将其放入视图中。

Now... Ok, if you are interested in picking some more about this, have a look at the "Practical symfony" tutorial: Day 15: Web Services There s some good stuff down there !

在REST风格中,只需在URI中添加.format,创建相对模板,Symfony Routing系统就可以为我们完成其余的工作。





相关问题
JQuery/MVC Search Issue

I have inherited a piece of work where the entry screen shows a summary of 20 calculated variables. E.g. Var A (250), Var B (79). Clicking on any of these links takes the user to a view with a ...

jQuery quicksearch plug-in tinkering with JSON

I ve implemented the quicksearch plugin by Rik Lomas and I love it for an application in a custom CMS I m building. I was wondering though, since I m going to have a bizillion items in the table if ...

JSON with classes?

Is there a standardized way to store classes in JSON, and then converting them back into classes again from a string? For example, I might have an array of objects of type Questions. I d like to ...

PHP json_decode question

i m trying to use json_decode to combine a few json objects and then re-encode it. my json looks like: { "core": { "segment": [ { "id": 7, "...

Converting JSON data to Java object

I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson(). Below is an example of what the string ...

热门标签