Skip to content

show-json-data-in-html

约 659 字大约 2 分钟

前端htmljson

2025-05-07

如何让JSON数据显示为Html表格的中,我们将介绍如何使用 JQuery 将 JSON 数据展示在 HTML 表格中的方法。JSON通常用于前后端数据传输。使用 jQuery 可以简化处理 JSON 数据的过程,并快速将其展示在网页上的表格中。

要使用JQuery,首先得引入它

可自行下载到本地,然后引用,也可以直接用CDN,本文使用CDN引用:

Staticfile CDN
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

百度 CDN
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

又拍云 CDN
<script src="https://upcdn.b0.upaiyun.com/libs/jquery/jquery-2.0.2.min.js"></script>

BootCDN
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

获取JSON数据

展示之前先准备好JSON数据,一般用JQuery的Ajax获取:

$.ajax({
  url: 'data.json',
  type: 'GET',
  dataType: 'json',
  success: function(data) {
    // 获取到 JSON 数据后的处理逻辑
  },
  error: function(xhr, status, error) {
    console.log(error);
  }
});

创建html页面及表格代码

新建html页面,命名为:index.html,方便浏览,在页面文件中写入:

<table id="data-table">
  <thead>
    <tr>
      <th>字段1</th>
      <th>字段2</th>
      <th>字段3</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

完善获取JSON文件的Ajax代码

将获取到的JSON数据,循环填充到html的表格中,注意行、列的数据匹配:

success: function(data) {
  var tbody = ('#data-table tbody');.each(data, function(index, item) {
    var row = ('<tr></tr>');
    row.append(('<td></td>').text(item.field1));
    row.append(('<td></td>').text(item.field2));
    row.append(('<td></td>').text(item.field3));

    tbody.append(row);
  });
}

完整代码如下:

将上面写的代码合并到一个文件中:index.html,就可以展示了,另外需要创建单独的JSON文件,放在与index.html同一目录下

JSON文件:

[
    {
        "name": "百度",
        "url": "www.runoob.com",
        "location": "中国"
    },
    {
        "name": "google",
        "url": "www.google.com",
        "location": "美国"
    },
    {
        "name": "微博",
        "url": "www.weibo.com",
        "location": "中国"
    }
]

index.html文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>显示 JSON 数据在 HTML 表格中</title>
  <script src="jquery.min.js"></script>
  <script>
    (document).ready(function() {.ajax({
        url: 'data.json',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
          var tbody = ('#data-table tbody');.each(data, function(index, item) {
            var row = ('<tr></tr>');
            row.append(('<td></td>').text(item.field1));
            row.append(('<td></td>').text(item.field2));
            row.append(('<td></td>').text(item.field3));

            tbody.append(row);
          });
        },
        error: function(xhr, status, error) {
          console.log(error);
        }
      });
    });
  </script>
</head>
<body>
  <table id="data-table">
    <thead>
      <tr>
        <th>name</th>
        <th>url</th>
        <th>location</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</body>
</html>

将上面的两段代码复制并保存成两个文件:data.json 和 index.html,然后在浏览器里打开index.html即可浏览。

联系我们(微信)