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

如何用JavaScript async-await结合HTML从API展示随机猫图?

实现通过async-await结合HTML获取并展示随机猫图

需求说明

使用JavaScript的async-await语法结合HTML,从API获取随机猫图并展示在网页中,而非仅输出图片URL到控制台。

修正后的代码实现

HTML代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Gif</title>
    <style>
        .container img {
            max-width: 100%;
            height: auto;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>这是一张随机猫图!</h1>
        <button onclick="apiFunction()">换一张猫图</button>
    </div>

    <script src="catGif.js"></script>
    <script>
        apiFunction();
    </script>
</body>
</html>

JavaScript代码(catGif.js)

const container = document.querySelector(".container");

async function apiFunction() {
    try {
        const res = await fetch("https://api.thecatapi.com/v1/images/search");
        if (!res.ok) {
            throw new Error(`请求失败,状态码:${res.status}`);
        }
        const result = await res.json();
        
        const existingImg = container.querySelector("img");
        if (existingImg) {
            existingImg.src = result[0].url;
        } else {
            const img = document.createElement("img");
            img.src = result[0].url;
            img.alt = "随机猫图";
            container.appendChild(img);
        }
    } catch (error) {
        console.error("获取猫图失败:", error);
        container.innerHTML += `<p style="color:red;">加载失败,请稍后重试</p>`;
    }
}

关键优化点

  • 调用apiFunction()确保页面加载时自动获取猫图,同时添加按钮支持手动刷新
  • 统一使用async/await语法替代原代码中混用的.then链式调用,逻辑更直观清晰
  • 用try/catch实现可靠的错误捕获,替换原代码错误的错误回调写法
  • 处理重复添加图片的问题,换图时直接替换已有图片的src,避免页面元素堆积
  • 添加图片alt属性和基础样式,提升页面可访问性与视觉体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:52:42