dougou5844 2016-05-26 15:28
浏览 63
已采纳

带有JSON的DataTable数据集

I'm trying to use DataTable to show all fields of my JSON, but I'm not understand how to use it.

I just need how to populate dataset correctly to read data.

<script>
        <?php
            var jqxhr = $.ajax({url: api_ricerca_ingredienti, type: "GET",dataType: "json", data: {all: 1, ln : "it",completo:"-1",conteggio: 1}} )
              var max=json.items.length;
              for (i=0;i<max;i++){
                var el=json.items[i];
              }
              $(".risultato_ricerca").click(function() {
                carica_ingrediente($(this).attr('data-id'));
              });
            })
            <?php }?>

            var dataSet = [
              /*HOW?*/
            ];

            $(document).ready(function() {
              $('#example').DataTable( {
                data: dataSet,
                columns: [
                  { title: "Nome" },
                  { title: "Stato" },
                  { title: "Home" },
                  { title: "Utente" },
                  { title: "Mi piace" },
                  { title: "Contributi" }
                ]
              } );
            } );
            </script>
            <table id="example" class="table table-responsive table-hover table-dynamic filter-head"></table>
  • 写回答

2条回答 默认 最新

  • dongmeng1875 2016-05-26 16:06
    关注

    First, two comments about your code. As @Patrick Q stated, your PHP tags are useless: you are writing Javascript, PHP is another things that has nothing to do with your code, so remove <?php and <?php }?>

    Then, i can't understand this code:

    for (i=0;i<max;i++){
       var el=json.items[i];
    }
    

    This for is completely useless. you cycle through every element in json.items without performing any operation. At the end you just store the last json.items in the el (without even using el in your code).

    By the way, your main question: As said in the official documentation, your dataSet must contain an array for every row of your table in the format:

    var dataSet = [
        ["john","italy","home","john",15,20],
        ["john","italy","home","john",15,20]
    ]
    

    This example will create two identical rows with random data inside.

    Assuming every item in your json has name country home user likes contribs fields you will need something like that:

    var dataSet = []; 
    for (i=0;i<json.items.length;i++){
         var el = [json.items[i].name,json.items[i].country, json.items[i].home, json.items[i].user, json.items[i].likes, json.items[i].contribs]
         dataSet[i] = el;
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器