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

如何在GitHub Pages用JS从JSON自动填充网页条目?

用纯JavaScript实现从JSON动态生成条目内容(适配GitHub Pages)

完全可以用纯JavaScript实现需求,不需要框架,完美适配GitHub Pages的静态部署环境,200条数据的量级也完全能轻松处理。

步骤1:准备JSON数据文件

创建一个entries.json文件,结构对应你的条目字段:

[
  {
    "imageSrc": "images/entry1.png",
    "imageAlt": "Image 1",
    "title": "First Entry",
    "rating": 4.5,
    "comment": "This is my first entry comment."
  },
  {
    "imageSrc": "images/entry2.png",
    "imageAlt": "Image 2",
    "title": "Second Entry",
    "rating": 5,
    "comment": "Great entry, highly recommend."
  }
]

步骤2:调整HTML结构

在你的页面中添加一个容器,用来承载所有动态生成的条目:

<!-- 新增条目容器 -->
<div id="entries-container"></div>

步骤3:编写JavaScript代码

在HTML页面中引入这段JS(或者放在<script>标签里),实现数据加载和DOM生成:

document.addEventListener('DOMContentLoaded', async function() {
  try {
    // 加载JSON数据
    const res = await fetch('entries.json');
    if (!res.ok) throw new Error('数据加载失败');
    const entries = await res.json();

    // 获取容器元素
    const container = document.getElementById('entries-container');

    // 循环生成每个条目
    entries.forEach(item => {
      const entryWrap = document.createElement('div');
      entryWrap.className = 'entry-wrapper'; // 对应你原有结构的外层div类名

      entryWrap.innerHTML = `
        <div class="image-container">
          <img src="${item.imageSrc}" alt="${item.imageAlt}">
        </div>
        <div class="entry-content">
          <div class="entry-title">${item.title}</div>
          <div class="entry-rating">Rating: ${item.rating}</div>
          <div class="entry-comment">Comment: ${item.comment}</div>
        </div>
      `;

      container.appendChild(entryWrap);
    });
  } catch (err) {
    console.error('加载条目出错:', err);
    const container = document.getElementById('entries-container');
    container.innerHTML = '<p>条目加载失败,请稍后重试。</p>';
  }
});

部署注意事项

  • 确保entries.json和HTML、JS文件的路径正确,比如都放在项目根目录下
  • GitHub Pages完全支持静态资源的fetch请求,无需额外配置
  • 200条数据的DOM生成在现代浏览器中毫无压力,不会有性能问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:43:11