小编典典

从Symfony中的Controller返回JSON数组

json

我正在尝试从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));过,但是得到相同的结果。


阅读 341

收藏
2020-07-27

共1个答案

小编典典

您需要执行此操作(基于先前的答案):

public function getAllCategoryAction() {
    $em = $this->getDoctrine()->getManager();
    $query = $em->createQuery(
        'SELECT c
        FROM AppBundle:Categoria c'
    );
    $categorias = $query->getArrayResult();

    $response = new Response(json_encode($categorias));
    $response->headers->set('Content-Type', 'application/json');

    return $response;
}

它适用于Doctrine作为数组返回的任何查询。

2020-07-27