如何在symfony3中返回ajax调用的json响应?

如何在symfony3中返回ajax调用的json响应?,symfony,Symfony,我正在使用symfony3: 我正在通过ajax调用调用一个方法: 控制器 /** * @Route("personnel/domainlist/{id}", name="ajax_method") * @Method("GET") */ public function domainlist(Request $request,$id){ $repository = $this->getDoctrine()->getRepositor

我正在使用symfony3:

我正在通过ajax调用调用一个方法:

控制器

/**
     * @Route("personnel/domainlist/{id}", name="ajax_method")
     * @Method("GET")
     */
    public function domainlist(Request $request,$id){
       $repository = $this->getDoctrine()->getRepository('AppBundle:ENTITYNAME');          
       $res=$repository->findBy(array('COLNAME' => $id));          
      // create a JSON-response with a 200 status code

      $response = new Response(json_encode($res));    
      $response->headers->set('Content-Type', 'application/json');
      return $response;
      die;
    }
从上面的代码中,我得到以下结果: 印刷品(港币);

AJax代码:

 $.ajax({
        url: "domainlist/" + pdoamin_id,      
        type: 'POST',
        dataType: 'json',        
         success: function(result) {
            alert(result);
             }
          });

  });

任何人都可以帮助我如何将json返回到symfony3中的ajax方法。在将答案推送到Response之前,您必须序列化答案。 有两种方法(至少我只知道两种方法)

  • (PHP版本>=5.4)
  • 在这两种变体中,json_encode函数将按预期工作


    我更喜欢第二种方法,因为它简单

    在将答案推送到响应之前,您必须将答案序列化。
    $repository = $this->getDoctrine()->getRepository('AppBundle:ENTITYNAME');          
           $res=$repository->findBy(array('COL_NAME' => $id));          
           $normalizer = new ObjectNormalizer();      
           $encoder = new JsonEncoder();
           $serializer = new Serializer(array($normalizer), array($encoder));
           $response=$serializer->serialize($res, 'json'); 
    
    有两种方法(至少我只知道两种方法)

  • (PHP版本>=5.4)
  • 在这两种变体中,json_encode函数将按预期工作


    我更喜欢第二种方法,因为它简单

    不确定Symfony 3是否有这个类,但是在Symfony 4中,您可以使用JsonResponse类

    $repository = $this->getDoctrine()->getRepository('AppBundle:ENTITYNAME');          
           $res=$repository->findBy(array('COL_NAME' => $id));          
           $normalizer = new ObjectNormalizer();      
           $encoder = new JsonEncoder();
           $serializer = new Serializer(array($normalizer), array($encoder));
           $response=$serializer->serialize($res, 'json'); 
    
    将类导入控制器

    use Symfony\Component\HttpFoundation\JsonResponse;
    
    然后在return语句中使用它的一个构造函数:

    return new JsonResponse($dataToReturn);
    

    这对我很有用。

    不确定Symfony 3是否有这个类,但在Symfony 4中,您可以使用JsonResponse类

    将类导入控制器

    use Symfony\Component\HttpFoundation\JsonResponse;
    
    然后在return语句中使用它的一个构造函数:

    return new JsonResponse($dataToReturn);
    
    这对我很管用