2015-09-27 103 views
0

所以,我和Ajax POST誰打電話在retunrn這樣的JSON響應的一個功能:學說收集JSON響應問題

$images = $this->getEntityManager()->getRepository('AppBundle:Image')->findBy(array(),array(),5); 
    $response = new JsonResponse(); 
    $response->setData(array(
     'images' => $images 
    )); 
    return $response; 

我得到的五行,但都是空的.. 。像下面的圖像中:

array

例如,i。從元件i中的數組返回一些屬性和它的工作原理:

$images = $this->getEntityManager()->getRepository('AppBundle:Image')->findBy(array(),array(),5); 
$response = new JsonResponse(); 
$response->setData(array(
    'images' => $images[0]->getSlug() 
)); 

return $response; 

success

這是簡單的Ajax代碼:

$.ajax({ 
    method: 'POST', 
    url: $("#scroll-down").attr("data-href"), 
    success: function(response) { 
      console.log(response); 
    }, 
    error: function() { 
      console.log(response); 
    } 
}).fail(function() { 
    console.log(response); 
}); 

回答

0

在Symfony的JsonResponse主要是爲php函數json_encode

json_encode不會編碼私有對象屬性的包裝。

<?php 

class Test { 
    private $a = null; 
    public $b = 3; 

    public function __construct($a) { 
     $this->a = $a; 
    } 
} 

$test = new Test(1); 

echo json_encode($test); 

這將輸出{"b":3}因爲$a是私人

所以,你應該使用第二種形式對您的問題或使用串行束

+0

權,學說ArrayColelction擁有一個私人屬性,叫做$ elemnts。解決方案可以使用適當的庫來序列化對象,如jms_serializer。這個庫使用反射,然後私有方法將被序列化! – erlangb