You need to enable JavaScript to run this app. 如何在HTML页面展示fetch获取的JSON数据到指定HERE位置
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML页面展示fetch获取的JSON数据到指定HERE位置

核心问题排查与修复
  • 元素绑定不匹配:代码中通过getElementById("servers")查找目标节点,但标记HERE位置的段落标签没有添加对应id="servers"属性,且该段落错误用</h1>闭合,会直接导致DOM解析错位,找不到要填充内容的位置。
  • 数据类型错误:innerHTML仅支持接收字符串类型值,如果直接将接口返回的JSON对象传入,浏览器会自动将对象转为默认的[object Object]字符串,完全无法展示有效数据。
  • 取值逻辑缺失:没有根据接口返回的JSON结构提取实际需要展示的数值,直接传递整个JSON对象也不具备可读的展示价值。

修正后可直接运行的代码示例

<div class="statistics">
    <div class="cards">
        <div class="card statistic" style="width: 18rem;">
            <div class="card-body">
                <!-- 给HERE位置加对应id,修正错误的闭合标签 -->
                <p id="servers" class="card-title" style="font-size: 50px !important;line-height: 15px !important;letter-spacing: -0.06em !important;font-weight: bold !important;">HERE</p>
                <p style="font-weight: bold !important;font-size: 20px !important;">servers</p>
            </div>
        </div>
    </div>
</div>

<script defer>
fetch("http://localhost:8080/bot/guilds")
    .then(res => {
        // 增加请求状态判断,避免非200响应也被当成有效数据处理
        if (!res.ok) throw new Error(`接口请求失败,状态码:${res.status}`)
        return res.json()
    })
    .then(json => {
        const targetNode = document.getElementById("servers")
        // 根据实际接口返回结构取值:如果要展示服务器总数就取对应字段,如果要展示完整JSON就用JSON.stringify转字符串
        // 示例逻辑:优先取guildCount字段,没有就展示完整JSON字符串
        const displayContent = json.guildCount ?? JSON.stringify(json)
        targetNode.textContent = displayContent
    })
    .catch(err => {
        // 增加异常捕获,避免请求失败时页面无反馈
        document.getElementById("servers").textContent = "数据加载失败"
        console.error("请求异常:", err)
    })
</script>

补充提示:如果运行后出现跨域拦截报错,需要在本地接口的响应头中配置允许当前前端页面的跨域访问规则,否则fetch请求会被浏览器安全策略阻断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.31 10:15:03