如何使用 JavaScript 和 HTML 中的 async-await 在我的网页上显示来自 API 的随机猫图像?
P粉617237727
P粉617237727 2023-09-04 15:22:47
[HTML讨论组]
<p>我正在编写一个程序,该程序从 API 调用以获取随机的猫图像。我希望能够在我的网页上显示该图像,而不仅仅是在控制台中显示网址。</p> <p>//这是我的 html(这确实很基本,但我只想让输出正常工作)</p> <pre class="brush:php;toolbar:false;">&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Cat Gif&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class=&quot;container&quot;&gt; &lt;h1&gt;This is a random image of a cat!&lt;/h1&gt; &lt;/div&gt; &lt;script src=&quot;catGif.js&quot;&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</pre> <p>//这是我的 JavaScript</p> <pre class="brush:php;toolbar:false;">let container = document.querySelector(&quot;.container&quot;); async function apiFunction() { await fetch(&quot;https://api.thecatapi.com/v1/images/search&quot;) .then(res =&gt; res.json()) .then((result) =&gt; { //items = result; let img = document.createElement(&quot;img&quot;); img.src = result[0].url; container.appendChild(img); }), (error) =&gt; { console.log(error); } }</pre></p>
P粉617237727
P粉617237727

全部回复(1)
P粉001206492

您没有调用您定义的函数。

<!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>
</head>

<body>
    <div class="container">
        <h1>This is a random image of a cat!</h1>
    </div>

    <script>
        let container = document.querySelector(".container");
        async function apiFunction() {
            await fetch("https://api.thecatapi.com/v1/images/search")
                .then(res => res.json())
                .then((result) => {
                    //items = result;
                    let img = document.createElement("img");
                    img.src = result[0].url;
                    container.appendChild(img);
                }),
                (error) => {
                    console.log(error);
                }
        }
        // Call the function
        apiFunction();
    </script>
</body>

</html>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号