【问题标题】:Fill html table based on JSON基于JSON填充html表格
【发布时间】:2016-07-03 23:15:53
【问题描述】:

我需要将调用 URL 的结果映射到 html 表中,但我想不出办法。

用于获取数据的 URL 是“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>

【问题讨论】:

  • 想从上面的这个 URL 中获取数据并使用 ajax 或 jquery 移动到 html 页面中的表格中。
  • 我知道这不是你想要的,但 AngularJS 会让这很容易,但你必须先学习 AgularJS 的基础知识,例如控制器、$scope 和$http。也许是为了未来的网络开发。
  • 这可能会给你一个线索:$('#table').append(' ' + json[i].reporting_year +' ' +json[i].cert +' ');
  • 如何检查我是否从该链接接收数据。我可以在我的 html 页面中打印数据吗?
  • 只要使用console.log(data);并通过在浏览器中单击 F12 检查您的控制台。

标签: jquery html json ajax


【解决方案1】:

您没有正确引用 json 对象。 json[i].name 确实应该是您要使用的键,例如 json[i].total_capacity_certified,因为 json 文件中没有 name 键,您的结果将显示为空。下面的代码循环遍历每个 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);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-11
    • 2014-05-08
    • 2016-01-26
    • 1970-01-01
    • 2012-10-30
    • 2016-03-03
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多