2015-09-27 100 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