【发布时间】:2015-03-24 08:08:07
【问题描述】:
我正在尝试从 Symfony 2 中的控制器返回 JSON 响应。例如,在 Spring MVC 中,我可以使用 @ResponseBody 注释获得 JSON 响应。我想得到一个 JSON 响应,不管它是 JSON 数组还是 Json 对象,然后在视图中使用 javascript 操作它。
我尝试下一个代码:
/**
* @Route(
* "/drop/getCategory/",
* name="getCategory"
* )
* @Method("GET")
*/
public function getAllCategoryAction() {
$categorias = $this->getDoctrine()
->getRepository('AppBundle:Categoria')
->findAll();
$response = new JsonResponse();
$response->setData($categorias);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
但我在浏览器中得到[{},{}] 作为响应。我也尝试使用$response = new Response(json_encode($categorias));,但我得到了相同的结果。
【问题讨论】:
-
你试过'return new JSONResponse($data);'吗?