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

如何在HTML页面中输出展示API接口返回的数据?

问题原因及修复方案

存在的问题

  • HTML标签未正确闭合:<div id="name"和<div id="calories"都缺少右尖括号>,导致DOM结构解析异常,JS无法正确获取对应元素。
  • 接口返回值取值错误:你调用的营养查询API返回结果是数组格式,数组的每一项才是营养数据对象,且对象不存在content字段,正确的字段就是name、calories等,你直接取response.content自然拿不到有效值。

修复后的代码

1. HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>  
    <div class="nutritionContainer">
        <div id="name"></div>
        <div id="calories"></div>
    </div>
    <script src="nutrition.js" type="module"></script>
</body>
</html>

2. nutrition.js代码

fetch("https://nutrition-by-api-ninjas.p.rapidapi.com/v1/nutrition?query=coffee", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "nutrition-by-api-ninjas.p.rapidapi.com",
        "x-rapidapi-key": "my_key"
    }
})
.then(response => response.json())
.then(response => {
    console.log(response);
    // 取返回数组的第一项数据,可根据需求遍历数组渲染多条
    const nutritionData = response[0];
    document.getElementById('name').innerHTML = nutritionData.name;
    document.getElementById('calories').innerHTML = nutritionData.calories + ' 卡路里';
})
.catch(err => {
    console.log(err);
});

补充说明

如果你的查询关键词返回多条营养数据,可以遍历response数组循环创建DOM节点渲染所有内容,当前示例仅取第一条数据做展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:42:00