📜  json 数据从服务器到 html 表 - Javascript (1)

📅  最后修改于: 2023-12-03 15:17:04.528000             🧑  作者: Mango

从服务器到 HTML 表的 JSON 数据介绍

当我们需要从服务器获取数据并在网页中显示时,JSON(JavaScript Object Notation)是一种常用的数据格式。在 JavaScript 中,我们可以使用 AJAX(Asynchronous JavaScript and XML)技术从服务器请求 JSON 数据并在网页中动态生成 HTML 表格。

下面是一个使用 JavaScript 和 AJAX 技术从服务器获取 JSON 数据,并将其呈现为 HTML 表格的简单示例代码。

// 异步请求 JSON 数据
const xhr = new XMLHttpRequest();
xhr.open('GET', 'url_to_json_data', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const jsonData = JSON.parse(xhr.responseText);
    createTable(jsonData);
  }
};
xhr.send();

// 根据 JSON 数据创建 HTML 表格
function createTable(jsonData) {
  const table = document.createElement('table');
  const headers = Object.keys(jsonData[0]);

  // 创建表头
  const thead = document.createElement('thead');
  const tr = document.createElement('tr');
  headers.forEach(header => {
    const th = document.createElement('th');
    th.textContent = header;
    tr.appendChild(th);
  });
  thead.appendChild(tr);
  table.appendChild(thead);

  // 创建表格内容
  const tbody = document.createElement('tbody');
  jsonData.forEach(data => {
    const tr = document.createElement('tr');
    headers.forEach(header => {
      const td = document.createElement('td');
      td.textContent = data[header];
      tr.appendChild(td);
    });
    tbody.appendChild(tr);
  });
  table.appendChild(tbody);

  // 将表格添加到页面
  document.body.appendChild(table);
}

在上述代码中,我们首先通过 XMLHttpRequest 对象发起异步 GET 请求以获取 JSON 数据。一旦响应状态为 200(成功),我们将获取的 JSON 数据解析为 JavaScript 对象,并将其传递给 createTable 函数。

createTable 函数接收一个包含 JSON 数据的数组作为参数,并使用 DOM 操作创建 HTML 表格。它首先创建表头(<thead> 标签)并添加每个表头单元格(<th> 标签)' ,然后创建表格内容( 标签)并添加每行数据( 标签)和对应的单元格(` 标签)。

最后,通过将表格添加到文档的 <body> 中,我们可以在网页上呈现 JSON 数据的 HTML 表格。

这是一个基本的示例,你可以根据具体需求进行修改和扩展。AJAX 和 JSON 数据在前端开发中扮演着重要角色,帮助我们实现动态页面内容的更新和交互。