doujiurong7210 2015-04-25 03:16
浏览 48

如何使用symfony2项目中的ajax解码JSON?

I'm currently working on a symfony2 and i'm sendig a JSON information about my products from my controller

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

}

the JSON from this URL ('http://localhost/BusinessTracker/web/app_dev.php/getProduitsJSON'):

[{"id":1,"refProduit":"1265466","nomProduit":"Yagourt","prixProduit":270,"stockProduit":10,"libelleProduit":"Yagourt D\u00e9lice"},{"id":2,"refProduit":"000001","nomProduit":"Nutella","prixProduit":4500,"stockProduit":15,"libelleProduit":"Chocolat Nutella"},{"id":3,"refProduit":"000002","nomProduit":"Lait D\u00e9lice","prixProduit":950,"stockProduit":30,"libelleProduit":"1L de Lait d\u00e9lice"}]

and now from the client side i want to decoding this JSON via ajax

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

and nothing happens. Please i need a help

  • 写回答

1条回答 默认 最新

  • duanhuang1967 2015-04-25 09:31
    关注

    I think your for-loop is slightly off:

    $.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');
            });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料