You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未掌握AJAX、jQuery时,如何用JavaScript读取服务器生成的本地JSON并生成HTML表格?

不用AJAX和jQuery的JSON读取与HTML渲染方案

别担心,没学AJAX和jQuery也能搞定你的需求,我分两种场景给你讲具体的实现方法:

一、读取本地静态JSON文件(自己存在本地的JSON)

浏览器直接打开本地HTML文件时(file://协议),出于安全限制不能直接请求本地文件,所以可以用这两种方法:

方法1:把JSON直接转成JS变量(最简单)

直接把JSON内容写成一个JS对象变量,存成单独的JS文件,这样不用读取文件就能直接用。比如:
创建data.js文件:

// 把你的JSON内容直接赋值给变量
const localData = {
  "products": [
    {"id": 1, "name": "笔记本", "price": 5999},
    {"id": 2, "name": "手机", "price": 3999}
  ]
};

然后在HTML里引入这个JS文件,之后就能直接用localData来渲染内容了:

<script src="data.js"></script>
<div id="content"></div>
<table id="productTable" border="1"></table>

<script>
  // 把数据写入HTML标签
  document.getElementById('content').innerHTML = `
    <h3>本地JSON数据:</h3>
    <pre>${JSON.stringify(localData, null, 2)}</pre>
  `;

  // 生成表格
  const products = localData.products;
  const table = document.getElementById('productTable');
  
  // 创建表头
  const headers = Object.keys(products[0]);
  const headerRow = document.createElement('tr');
  headers.forEach(header => {
    const th = document.createElement('th');
    th.textContent = header;
    headerRow.appendChild(th);
  });
  table.appendChild(headerRow);

  // 创建表体行
  products.forEach(item => {
    const row = document.createElement('tr');
    headers.forEach(header => {
      const td = document.createElement('td');
      td.textContent = item[header];
      row.appendChild(td);
    });
    table.appendChild(row);
  });
</script>

方法2:让用户手动选择本地JSON文件(用FileReader API)

如果需要用户自己选择本地的JSON文件,用浏览器原生的FileReader API就行,完全不用AJAX:

<!-- 文件选择框,只允许选JSON文件 -->
<input type="file" id="jsonPicker" accept=".json">
<div id="dataDisplay"></div>
<table id="resultTable" border="1"></table>

<script>
  const filePicker = document.getElementById('jsonPicker');
  const displayArea = document.getElementById('dataDisplay');
  const resultTable = document.getElementById('resultTable');

  // 监听文件选择事件
  filePicker.addEventListener('change', function(e) {
    const selectedFile = e.target.files[0];
    if (!selectedFile) return;

    // 创建FileReader读取文件
    const reader = new FileReader();
    reader.onload = function(event) {
      try {
        // 把读取到的文本解析成JS对象
        const jsonData = JSON.parse(event.target.result);
        
        // 显示原始数据
        displayArea.innerHTML = `
          <h3>读取到的JSON内容:</h3>
          <pre>${JSON.stringify(jsonData, null, 2)}</pre>
        `;

        // 生成表格(假设数据是数组,或者包含数组属性)
        const tableData = jsonData.products || jsonData;
        if (Array.isArray(tableData) && tableData.length > 0) {
          // 清空之前的表格内容
          resultTable.innerHTML = '';

          // 生成表头
          const headers = Object.keys(tableData[0]);
          const headerRow = document.createElement('tr');
          headers.forEach(h => {
            const th = document.createElement('th');
            th.textContent = h;
            headerRow.appendChild(th);
          });
          resultTable.appendChild(headerRow);

          // 生成每行数据
          tableData.forEach(item => {
            const row = document.createElement('tr');
            headers.forEach(h => {
              const td = document.createElement('td');
              td.textContent = item[h];
              row.appendChild(td);
            });
            resultTable.appendChild(row);
          });
        }
      } catch (err) {
        displayArea.innerHTML = `<p style="color: red;">JSON解析出错:${err.message}</p>`;
      }
    };

    // 以文本形式读取文件
    reader.readAsText(selectedFile);
  });
</script>

二、读取服务器端生成的JSON文件

如果是服务器生成的JSON(比如后端接口返回的JSON,或者服务器上的JSON文件),这里有两个方案:

方法1:用原生fetch API(超简单,学5分钟就能会)

fetch是浏览器原生的HTTP请求API,比AJAX的老写法简单太多,就算没学AJAX也能快速上手。前提是你的HTML要放在服务器环境下(比如用Node.js的http-server,或者XAMPP),不能直接用file://打开。

示例代码:

<div id="serverDataDisplay"></div>
<table id="serverTable" border="1"></table>

<script>
  // 替换成你的服务器JSON文件路径或接口地址
  fetch('/api/generated-data.json')
    .then(response => {
      if (!response.ok) {
        throw new Error('获取数据失败,请检查路径');
      }
      // 直接把响应解析成JS对象
      return response.json();
    })
    .then(jsonData => {
      // 显示数据
      document.getElementById('serverDataDisplay').innerHTML = `
        <h3>服务器返回的数据:</h3>
        <pre>${JSON.stringify(jsonData, null, 2)}</pre>
      `;

      // 生成表格
      const tableData = jsonData.users || jsonData;
      if (Array.isArray(tableData) && tableData.length > 0) {
        const table = document.getElementById('serverTable');
        table.innerHTML = '';

        // 表头
        const headers = Object.keys(tableData[0]);
        const headerRow = document.createElement('tr');
        headers.forEach(h => {
          const th = document.createElement('th');
          th.textContent = h;
          headerRow.appendChild(th);
        });
        table.appendChild(headerRow);

        // 表行
        tableData.forEach(item => {
          const row = document.createElement('tr');
          headers.forEach(h => {
            const td = document.createElement('td');
            td.textContent = item[h];
            row.appendChild(td);
          });
          table.appendChild(row);
        });
      }
    })
    .catch(err => {
      document.getElementById('serverDataDisplay').innerHTML = `<p style="color: red;">出错了:${err.message}</p>`;
    });
</script>

方法2:服务器端渲染(完全不用前端发请求)

如果你的项目有后端(比如Node.js、PHP),可以让后端提前读取JSON数据,直接把数据嵌入到HTML里返回给浏览器,前端直接用就行:

比如用Node.js的Express框架示例(后端代码):

const express = require('express');
const fs = require('fs');
const app = express();

app.get('/', (req, res) => {
  // 读取服务器上的JSON文件(或者后端生成JSON数据)
  fs.readFile('./generated-data.json', 'utf8', (err, rawData) => {
    if (err) {
      res.send('读取服务器数据失败');
      return;
    }
    const jsonData = JSON.parse(rawData);

    // 把数据直接嵌入到HTML的JS变量中
    const htmlPage = `
      <!DOCTYPE html>
      <html>
      <head>
        <title>服务器渲染数据</title>
      </head>
      <body>
        <div id="display"></div>
        <table id="renderedTable" border="1"></table>
        <script>
          // 直接使用后端传过来的数据
          const serverGeneratedData = ${JSON.stringify(jsonData)};
          
          // 渲染内容
          document.getElementById('display').innerHTML = \`
            <h3>服务器渲染的JSON数据:</h3>
            <pre>\${JSON.stringify(serverGeneratedData, null, 2)}</pre>
          \`;

          // 生成表格
          const tableData = serverGeneratedData.users || serverGeneratedData;
          if (Array.isArray(tableData) && tableData.length > 0) {
            const table = document.getElementById('renderedTable');
            const headers = Object.keys(tableData[0]);
            const headerRow = document.createElement('tr');
            headers.forEach(h => {
              const th = document.createElement('th');
              th.textContent = h;
              headerRow.appendChild(th);
            });
            table.appendChild(headerRow);

            tableData.forEach(item => {
              const row = document.createElement('tr');
              headers.forEach(h => {
                const td = document.createElement('td');
                td.textContent = item[h];
                row.appendChild(td);
              });
              table.appendChild(row);
            });
          }
        </script>
      </body>
      </html>
    `;

    res.send(htmlPage);
  });
});

app.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000');
});

内容的提问来源于stack exchange,提问作者Aryan Arora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:41:41