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

如何通过jQuery动态在div中嵌入产品div并渲染API返回数据

解决方案:动态生成产品并嵌入到.row容器

先确认静态产品结构示例

假设你的静态产品div结构如下(可根据实际结构调整):

<div class="col-md-4 product-item">
  <div class="card">
    <img src="product-image.jpg" class="card-img-top" alt="产品名称">
    <div class="card-body">
      <h5 class="card-title">产品名称</h5>
      <p class="card-text">产品描述</p>
      <p class="card-price">¥99.00</p>
      <button class="btn btn-primary">加入购物车</button>
    </div>
  </div>
</div>

正确的实现代码

结合fetch和jQuery,完整的动态生成逻辑如下:

$(document).ready(function() {
  // 替换为你的实际API地址
  const productApi = '/api/get-products';

  fetch(productApi)
    .then(res => {
      // 校验响应状态,避免错误响应继续处理
      if (!res.ok) throw new Error(`请求失败:${res.status}`);
      return res.json();
    })
    .then(products => {
      const $row = $('.row');
      $row.empty(); // 清空原有内容(可选,按需保留或移除)

      // 遍历产品数组生成DOM元素
      products.forEach(prod => {
        // 用模板字符串生成产品HTML,替换字段为API返回的属性
        const prodHtml = `
          <div class="col-md-4 product-item">
            <div class="card">
              <img src="${prod.image || 'default-img.jpg'}" class="card-img-top" alt="${prod.name}">
              <div class="card-body">
                <h5 class="card-title">${prod.name}</h5>
                <p class="card-text">${prod.desc || '暂无描述'}</p>
                <p class="card-price">¥${prod.price?.toFixed(2) || '0.00'}</p>
                <button class="btn btn-primary">加入购物车</button>
              </div>
            </div>
          </div>
        `;
        // 将生成的产品HTML追加到.row容器
        $row.append(prodHtml);
      });
    })
    .catch(err => {
      console.error('加载产品出错:', err);
      // 加载失败时显示提示
      $('.row').html('<div class="col-12 text-center text-danger">产品加载失败,请稍后重试</div>');
    });
});

常见问题排查

  1. DOM加载时机错误:如果代码在DOM渲染前执行,.row元素还不存在,导致无法插入。必须把代码放在$(document).ready()内,或者页面底部</body>标签前。
  2. API响应处理不当:未校验响应状态、未将响应转为JSON,或者API返回的不是数组。打开浏览器控制台→Network标签,查看API请求的响应内容和状态码,确认数据格式正确。
  3. 模板字符串语法错误:检查变量拼写(比如prod.imgae应为prod.image)、引号嵌套(模板字符串用反引号`,内部变量用${}包裹)。
  4. jQuery选择器错误:确认页面中存在且正确匹配.row元素,可通过console.log($('.row').length)检查是否选中目标元素。

内容的提问来源于stack exchange,提问作者Smitty's

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:45:46