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

如何将JSON文件数据导入HTML页面实现动态商品展示?

如何将JSON商品数据动态渲染到HTML页面

问题背景

开发在线商店时,需要将存储在JSON文件中的商品信息替换HTML里的静态商品卡片,实现动态展示。现有JSON文件(products.json)包含7个商品的ID、名称、图片路径、原价和促销价;需替换的静态卡片使用Bootstrap样式。

解决方案:原生JavaScript动态渲染

以下是无需框架的实现步骤,直接用浏览器原生API完成:

1. 调整HTML结构,添加商品容器

首先在index.html中预留一个容器,用来承载动态生成的商品卡片:

<!-- 在页面合适位置添加这个容器 -->
<div id="products-container" class="row gx-4 gx-lg-5 row-cols-2 row-cols-md-3 row-cols-xl-4 justify-content-center"></div>

2. 编写JavaScript代码获取并渲染数据

在HTML的<script>标签中(或外部JS文件),使用fetch API读取JSON数据,循环生成商品卡片并插入容器:

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
  // 获取商品容器元素
  const container = document.getElementById('products-container');
  
  // 读取JSON文件
  fetch('./products.json')
    .then(response => response.json())
    .then(products => {
      // 遍历每个商品数据
      products.forEach(product => {
        // 判断是否显示促销徽章
        const saleBadge = product.salePrice < product.price 
          ? '<div class="badge bg-dark text-white position-absolute" style="top: 0.5rem; right: 0.5rem">Sale</div>'
          : '';
        
        // 格式化价格为美元格式
        const originalPrice = `$${product.price.toFixed(2)}`;
        const salePrice = `$${product.salePrice.toFixed(2)}`;
        
        // 生成商品卡片HTML
        const cardHTML = `
          <div class="col mb-5">
            <div class="card h-100 position-relative">
              ${saleBadge}
              <img class="card-img-top" width="450" height="200" src="${product.image}" alt="${product.productName}" />
              <div class="card-body p-4">
                <div class="text-center">
                  <h5 class="fw-bolder">${product.productName}</h5>
                  <div class="d-flex justify-content-center small text-warning mb-2">
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                    <div class="bi-star-fill"></div>
                  </div>
                  ${product.salePrice < product.price ? `<span class="text-muted text-decoration-line-through">${originalPrice}</span>` : ''}
                  ${salePrice}
                </div>
              </div>
              <div class="card-footer p-4 pt-0 border-top-0 bg-transparent">
                <div class="text-center"><a class="btn btn-outline-dark mt-auto" href="#">Add to cart</a></div>
              </div>
            </div>
          </div>
        `;
        
        // 将卡片插入容器
        container.innerHTML += cardHTML;
      });
    })
    .catch(error => console.error('加载商品数据失败:', error));
});

3. 注意事项

  • 确保products.json文件路径正确:如果JSON文件和index.html在同一目录,使用./products.json;如果在public目录,调整路径为./public/products.json(根据实际目录结构修改)。
  • 本地测试时,避免直接打开HTML文件(会有跨域限制),建议使用本地服务器(比如VS Code的Live Server插件)运行项目。
  • 价格格式化使用toFixed(2)确保显示两位小数,符合货币展示规范。
  • 促销徽章仅在促销价低于原价时显示,避免不必要的元素渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:47:53