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

如何遍历API返回的50条商品数据并渲染为HTML列表li标签

商品列表渲染解决方案

修改说明

  • 保留原有API调用逻辑,仅修改响应数据渲染部分
  • 把给定的列表项模板抽离为JS模板字符串,保留所有原有样式类
  • 遍历返回的商品数据,逐个替换模板内的占位符
  • 所有渲染完成的列表项包裹在<ul>标签内,整体插入到id为result的容器中

完整可运行代码

<div class="column right" id="result">
</div>
<script type="text/javascript">
        function callAliExpressApi(index) {
          let url = '';
          if (index == 1) url = "/api/get-products";
          else if (index == 2)  url = "/api/get-hotproducts";
          else if (index == 3)  return;
          else if (index == 4)  url = "/api/get-categories";
          else if (index == 5)  url = "/api/get-featuredpromo-info";
          else if (index == 6)  return;
          else if (index == 7)  return;
    
          $.get(url, function(data, status){
            // 商品列表项模板
            const itemTemplate = `
<li class="layer-slide gallery-book-slide">
    <div>
      <span class="gallery-book-list-img">
        <img src="{productimage}">
      </span>
      <div class="layer-region">
        <a href="#" target="_blank">
          <div class="layer-inner">{productname}</div>
        </a>
      </div>
      <a href="{producturl}" target="_blank" class="gallery-book-product-text" title="">{producttitle}</a>
      <div class="gallery-book-author" title=""></div>
              <div class=" gallery-book-product-price">
        <div>
          <i>
            <span>¥</span>{productprice} </i>
          <span></span>
        </div>
      </div>
    </div>
  </li>
`
            let listContent = '<ul>'
            // 遍历商品数据替换占位符,若API返回的商品字段名不同,自行调整替换的对应字段即可
            data.forEach(product => {
              let renderedItem = itemTemplate.replace('{productimage}', product.productimage)
                                        .replace('{productname}', product.productname)
                                        .replace('{producturl}', product.producturl)
                                        .replace('{producttitle}', product.producttitle)
                                        .replace('{productprice}', product.productprice)
              listContent += renderedItem
            })
            listContent += '</ul>'
            $("#result").html(listContent);
          });
        }
      </script>

效果参考

效果示意图

内容的提问来源于stack exchange,提问作者Shaiful Rizal Shaharudin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:36:03