根据JSON填写html表

时间:2016-03-17 14:26:01

标签: jquery html json ajax

我需要将调用URL的结果映射到html表中,但我无法找到一种方法。

用于获取数据的网址是“https://abcdefghi/h5s5-hcxg.json”。那么,任何人都可以帮助我如何从这个URL获取数据到表格中吗?

请参阅我的代码:

<script>
        $.ajax({
            url: "https://abcdefghij.json",
            //force to handle it as text
            dataType: "text",
            success: function(data) {

                //data downloaded so we call parseJSON function 
                //and pass downloaded data
                var json = $.parseJSON(data);
                //now json variable contains data in json format
                //let's display a few items
                for (var i=0;i<json.length;++i)
                {
                    $('#results').append('<div class="name">'+json[i].name+'</>');
                }
            }
        });
</Script>

1 个答案:

答案 0 :(得分:3)

您没有正确引用json对象。 json [i] .name应该是你在例如json [i] .total_capacity_certified之后的关键,因为json文件中没有名称键,你的结果将显示为空。下面的代码循环遍历每个json对象,并为每个键创建一个新的表列

<table id="results">
   <tr>
      <td></td>
   </tr>
</table>

的.js

$.ajax({
  url: "https://health.data.ny.gov/resource/h5s5-hcxg.json",
  //force to handle it as text
  dataType: "text",
  success: function(data) {

    //data downloaded so we call parseJSON function 
    //and pass downloaded data
    var json = $.parseJSON(data);
    //now json variable contains data in json format
    //let's display a few items

    // we'll put all our html in here for now
    var html = '';
    for (var i=0;i<json.length;++i)
    {
      // if on first loop, create the col headers
      if(i===0){
        html += '<thead><tr>';
        $.each(json[i], function(key, value){
            html += '<td>'+key+'</td>' ;
          });
        html += '</thead></tr>';
      }

      // loop through all the json objects and for every key add a column with the value
        html += '<tr>';
        $.each(json[i], function(key, value){
          html += '<td>'+value+'</td>' ;
        });
      html += '</tr>';
    }
    // push all the html in one go to the page
    $('#results').append(html);
  }
});