2017-11-20 3 views
2

내가 JSON
으로 저장소 개체를 보내려고에 JSON으로 저장소에서 개체를 반환하는 방법 내 컨트롤러 코드 :Symfony3

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

내 자바 스크립트 코드 : 여기

$(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으로 저장소 객체를 어떻게 보낼 수 있습니까? 어느 하나 도와주세요. 미리 감사드립니다 ...

편집 : 내가하려고하면이

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

을 보여주는

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

콘솔과 같은 코드 아래에 시도 잘못 어디로 가는지 잘 모릅니다

xmlHttpRequest 전에 저장소 객체 찾기

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

여기에 적절한 오브젝트를 보여주는하지만 잘못

Edit2가가는 무슨 난 정말 JSON을 모르는 : 나는 모든 사람을 위해 ... 지금은 잘 작동 것 같은 감사를 수행

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

... 등 유용한 응답

+0

내 대답이 도움이 되었습니까? 예, 동의하십시오 :) – Mcsky

답변

1

JsonResponse 클래스를 사용해야합니다. 당신이 JSON으로 객체를 변환하기위한 사용해야 Serializer Component

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

+0

나는 JsonResponse 클래스를 시도했습니다. 하지만 나는 500 (내부 서버 오류)를 받고있다 – somesh

+0

어떻게 사용 했습니까? 당신은 저를 코멘트로 볼 수 있습니까? –

+0

return $ json = new JsonResponse (json_encode (array ('bedroom'=> ​​$ 침실))); 이 – somesh

2

심포니 배송 (당신의 SF 버전을 선택합니다).

응용 프로그램/설정/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 문자열이어야합니다. 뭔가 잘못 되었다면 알려주세요. :) 도움이 되었기를 바랍니다.

+0

응답 주셔서 감사합니다 결과 개체가 표시되지 않습니다. 리소스를로드하지 못했습니다 : 서버가 500 (내부 서버 오류)의 상태로 응답했습니다. – somesh

+0

필자는 'serializer' 서비스를 다시 시도하십시오. 오류가 발생하면 귀하의 의견에 연결하십시오 :) – Mcsky

+0

@somesh를 얻는 데있어 어떤 오류가 발생합니까? 많은 다른 것들에 대해서는 오류가 발생할 수 있습니다. 맥 스키의 대답. – Andy

0

symfony3을 사용하고 있는데, 제 경우에는 이것이 저에게 효과적입니다.

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

귀중한 응답 주셔서 감사합니다 @habibun 내가 했어 JSON 배열에서 객체 속성을 보내는 방법 – somesh