如何在Symfony3上将Repository中的对象作为Json返回

时间:2017-11-20 06:43:08

标签: javascript jquery json ajax symfony

我试图将存储库对象作为json发送 我的控制器代码:

if($request->isXmlHttpRequest()){   
        $data = $request->request->get('id');
        $bedroom = $em->getRepository('EpitaHousingBundle:Bedroom')->findOneBy(array('id'=>$data));

        $this->container->get('logger')->addInfo('somesh');

        return $json = new Response(json_encode(array('bedroom' => $bedroom)));   
       } 

我的javascript代码:

$(document).ready(function(){            
     var id_select = $('#bedroom_view_bedroom').val();        
     $.ajax({
            type: 'POST', 
            url: '{{ (path('listingview', {'id': id})) }}',
            contentType: 'application/x-www-form-urlencoded',
            data: {id:id_select}, 
        success: function(result,status,xhr){
           var inst_arr = JSON.parse(result);
           console.log(inst_arr);
          },
        error: function(xhr, status, error) {     
                console.log(status);
            } 
        }); 
  });

这里我得到空对象作为回应。如何使用symfony3将存储库对象作为json发送。帮助我任何人。提前谢谢......

编辑:

我不知道它在哪里出错我尝试下面的代码如

if ($request->isXmlHttpRequest()) {
        $data = $request->request->get('id');
        $bedroom = $em->getRepository('EpitaHousingBundle:Bedroom')->findOneBy(array('id' => $data));
        if (null === $bedroom) {
            $bedroomJson = '';
        }
        $this->container->get('logger')->addInfo('somesh');  
        $serializer = $this->container->get('serializer');           
        $bedroomJson = $serializer->serialize($bedroom, 'json');

        return new Response($bedroomJson, Response::HTTP_OK, ['content-type' => 'application/json']);
    }

控制台显示

jquery.min.js:4 POST http://localhost/epitahousing/web/app_dev.php/provider/listing/view/8 500 (Internal Server Error)error

如果我尝试在xmlHttpRequest之前找到存储库对象,比如

$bedroom = $em->getRepository('EpitaHousingBundle:Bedroom')->findOneBy(array('id' => '12'));
    if ($request->isXmlHttpRequest()) {           
      //code
    }

这里显示了正确的对象,但我真的不知道json出了什么问题

Edit2:

$bedroom = $this->em->getRepository('EpitaHousingBundle:Bedroom')->findOneBy(array('id'=>$data));

        $output['rentamount'] = $bedroom->getRentamount();
        $output['rentcurrency'] = $bedroom->getRentcurrency()->getValue();
        $output['rentduration'] = $bedroom->getRentduration()->getValue();
        $output['bondamount'] = $bedroom->getBondamount();
        $output['bondcurrency'] = $bedroom->getBondcurrency()->getValue();
        $output['leaseminduration'] = $bedroom->getLeaseminduration()->getValue();
        $output['leasemaxduration'] = $bedroom->getLeasemaxduration()->getValue();
return $json = new Response(json_encode($output));

我这样做了,现在工作得很好...... 感谢每一个......这样一个有价值的回应

3 个答案:

答案 0 :(得分:2)

Symfony附带Serializer Component(选择您的Sf版本),您应将其用于将对象转换为json。

应用/配置/ config.yml

启用序列化程序组件

serializer:
        enabled: true

您的控制器

if($request->isXmlHttpRequest()){   
    $data = $request->request->get('id');
    $bedroom = $em->getRepository('EpitaHousingBundle:Bedroom')->findOneBy(array('id'=>$data));
    if(null === $bedroom) {
        // return some error response
    }
    $this->container->get('logger')->addInfo('somesh');
    $serializer = $this->container->get('serializer');
    $bedroomJson = $serializer->serialize($bedroom, 'json');

    return new Response($bedroomJson, Response::HTTP_OK, ['content-type' => 'application/json']);   
}

$bedroomJson应该是表示实体对象的json字符串。如果出现问题,请告诉我:)我希望它有所帮助!

答案 1 :(得分:1)

您应该使用JsonResponse类;

return new JsonResponse(array('bedroom' => $bedroom));

答案 2 :(得分:0)

我正在使用symfony3,就我而言,这对我有用。

$obj = "your object";
$data = $this->get('serializer')->serialize($obj, 'json');
return new Response($data);