Php 如何从symfony2项目中使用ajax解码JSON?
我目前正在开发一个symfony2,我正在从我的控制器发送一个关于我的产品的JSON信息Php 如何从symfony2项目中使用ajax解码JSON?,php,jquery,ajax,json,symfony,Php,Jquery,Ajax,Json,Symfony,我目前正在开发一个symfony2,我正在从我的控制器发送一个关于我的产品的JSON信息 public function getProduitsOnJSONAction() { $em = $this->container->get('doctrine')->getEntityManager(); $produits = $em->getRepository('BTBundle:Produit')->findAll(); //start b
public function getProduitsOnJSONAction()
{
$em = $this->container->get('doctrine')->getEntityManager();
$produits = $em->getRepository('BTBundle:Produit')->findAll();
//start bloc reponse json
$encoders = array(new JsonEncoder());
$normalizers = array(new GetSetMethodNormalizer());
$serializer = new Serializer($normalizers, $encoders);
// passed data $produits
$response = new Response($serializer->serialize($produits, 'json'));
$response->headers->set('Content-Type', 'application/json');
return $response;
// end bloc json response
}
此URL中的JSON:
现在,在客户端,我想通过ajax解码这个JSON
$.getJSON('http://localhost/BusinessTracker/web/app_dev.php/getProduitsJSON', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
什么也没发生。请告诉我需要帮助我认为您的for循环有点不正常:
$.getJSON('http://localhost/BusinessTracker/web/app_dev.php/getProduitsJSON', function(data) {
var items = [];
data.each(function(obj) {
items.push('<li id="' + obj.id + '">' + obj.nomProduit + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
您在控制台中是否收到任何错误?是否尝试在控制台中打印数据以帮助调试?$。getJSON'http://localhost/BusinessTracker/web/app_dev.php/getProduitsJSON,当您访问http://localhost/BusinessTracker/web/app_dev.php/getProduitsJSON 你有JSON输出吗?是的,当我访问iget JSON输出时
$.getJSON('http://localhost/BusinessTracker/web/app_dev.php/getProduitsJSON', function(data) {
var items = [];
data.each(function(obj) {
items.push('<li id="' + obj.id + '">' + obj.nomProduit + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});