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

如何使用JavaScript调用API获取并插入页面图片 新手开发问题

代码存在的问题及修复方案

  • 变量名大小写不匹配:你声明的DOM元素变量是name,后续赋值时错误使用了大写开头的Name,JavaScript严格区分大小写,会导致变量未定义报错。
  • 事件监听绑定位置错误:downloadImage按钮的点击事件被嵌套在randomName按钮的点击回调内,必须先点击一次「Randomize」按钮,图片下载按钮才会生效,不符合交互逻辑,需要移到全局作用域。
  • 原生API调用缺前缀:getElementById是document对象的方法,你漏写了document.前缀,会导致方法未定义报错。
  • API返回值处理错误:你调用的星战图片API返回的是包含所有角色信息的数组,不能直接读取image属性,需要根据生成的随机ID取下标对应的数据,再提取image字段。
  • 图片渲染逻辑错误:拿到图片URL后不能直接赋值给innerHTML,需要创建<img>标签并将URL赋值给src属性,才能正常渲染图片。

修正后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <strong>Name</strong>
    <div id = "Name" ></div>
    <strong>Eye Colour:</strong><div id = "eye_colour"></div>
    <strong>Birth Year:</strong>   <div id="hey"></div>
    <strong>Image</strong><div id="img"> </div>
    <button class="randomName">Randomize</button>
    <button class="downloadImage">Download Image</button>
</body>   
<script>
    const nameEl = document.getElementById("Name")
    const eye_colour = document.getElementById("eye_colour")
    const hey = document.getElementById("hey")
    const imgEl = document.getElementById('img')
    const randomNameBtn = document.querySelector('.randomName');
    const downloadImgBtn = document.querySelector('.downloadImage')
    // 提前缓存角色图片数据,避免重复请求
    let characterImgList = null

    randomNameBtn.addEventListener("click", (e) =>{
        e.preventDefault()
        nameEl.innerHTML ='<em>Loading....</em>'
        eye_colour.innerHTML= '<em>Loading....</em>'
        hey.innerHTML = '<em>Loading....</em>'
        const randomNumber= Math.ceil(Math.random() * 83)
        fetch(`https://swapi.dev/api/people/${randomNumber}`)
        .then(response=>response.json())
        .then(CharacterData =>{
            nameEl.innerHTML =CharacterData['name']
            eye_colour.innerHTML= CharacterData['eye_color']
            hey.innerHTML = CharacterData['birth_year']
        })
    })

    downloadImgBtn.addEventListener("click", (e)=>{
        imgEl.innerHTML = '<em>加载图片中...</em>'
        // 如果已经请求过数据就直接用缓存
        if(characterImgList) {
            renderRandomImg()
            return
        }
        fetch(`https://akabab.github.io/starwars-api/api/all.json`)
        .then(response=>response.json())
        .then(idData =>{
            characterImgList = idData
            renderRandomImg()
        })
    })

    function renderRandomImg() {
        const randomId = Math.ceil(Math.random() * 88)
        const imgUrl = characterImgList[randomId].image
        imgEl.innerHTML = `<img src="${imgUrl}" alt="角色图片" style="max-width: 300px;">`
    }
</script>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:15:01