2016-05-09 22 views
0

我想通過jsonresponse將我的「產品」表中的所有記錄提取到我的ajax腳本中,該腳本可以在我的樹枝模板中進一步加載,但截至目前返回的值是通過JSON空,Symfony:無法通過jsonresponse獲取表中的所有行

以下是我的控制器:

public function showAction($slug){ 
    $em = $this->getDoctrine()->getManager(); 
     if($slug == 'prod'){ 
      $repo = $em->getRepository('SystemBundle:Products'); 
      $q = $repo->createQueryBuilder('u'); 
      return new JsonResponse($q); 
     } 

} 

以下是我的AJAX功能:

<script> 
    function fetchprod() { 
     $.ajax({ 
      url: "/show/prod", 
      dataType: "json" 
     }).success(function(data){ 
      $('#contaiber').html(JSON.stringify(data.sum)); 
     }); 
    } 
    fetchprod() 
    setInterval(function() {fetchprod()}, 3000); 
</script> 

,這是我的標記(只是一個容器的div看到返回什麼):

<div id="container"> 

</div> 

我不是DIV中得到任何東西,但是當我輸入網址,我可以看到「{}」頁面(基本是空白陣列)上顯示。

我該如何解決這個問題? 謝謝

回答

1

試試這個

$em = $this->getDoctrine()->getManager(); 
if($slug == 'prod'){ 
    $repo = $em->getRepository('SystemBundle:Products'); 
    $q = $repo->createQueryBuilder('u') 
    ->getQuery(); 
    $products = $q->getResult(); 
    return new JsonResponse($products); 
} 
+0

輸出:[{}],但空白數組! –

+0

你在$ product結果中獲得了什麼?你是否試圖採取轉儲()。可能沒有數據從選定的表中返回。 –

0

$result = $q->getQuery()->getOneOrNullResult(); to get one record $result = $q->getQuery()->getResult(); to get all record 可能是你需要得到的結果,然後再通過json傳遞回來。

+0

我已經使用$ result = $ q-> getResult();,我得到了「[{}]」作爲輸出!它仍然返回一個空白數組! –

0

試試這個:

$em = $this->getDoctrine()->getManager(); 
    if($slug == 'prod'){ 
     $repo = $em->getRepository('SystemBundle:Products'); 
     $q = $repo->createQueryBuilder('u') 
      ->getQuery() 
      ->getArrayResult(); 
     return new JsonResponse($q); 
    } 

簡單,作品!