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

Node.js环境下如何将API返回对象按指定格式在EJS页面渲染

解决方案

你只需要修改 /public/index.ejs 中的 showResult 函数即可,后端 app.js 的返回逻辑无需调整。

单条产品渲染(适配原有分页逻辑)

原有代码是按分页每次渲染单个产品,直接修改拼接的内容为你需要的DOM结构即可:

function showResult() {
  const item = window.items[window.currentPage];
  // 拼接目标结构,已补全原示例中缺失的span闭合标签
  const result = `<div>price : ${item.product_price} <span>${item.product_name}</span></div>`;
  $("#result").html(result);
}

批量渲染所有产品

如果需要一次性渲染接口返回的全部产品列表,改为遍历产品数组拼接即可:

function showResult() {
  let result = '';
  window.items.forEach(product => {
    result += `<div>price : ${product.product_price} <span>${product.product_name}</span></div>`;
  })
  $("#result").html(result);
}

注意事项

  • 确保接口返回的产品对象中存在 product_price 和 product_name 两个字段,如果实际返回的字段名不同,替换代码中对应的字段名即可。

内容的提问来源于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.27 04:54:08