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
相关产品推荐
相关产品推荐

