如何使用 JavaScript 和 HTML 中的 async-await 在我的網頁上顯示來自 API 的隨機貓圖像?
P粉617237727
P粉617237727 2023-09-04 15:22:47
0
1
649
<p>我正在編寫一個程序,該程序從 API 呼叫以獲取隨機的貓圖像。我希望能夠在我的網頁上顯示該圖像,而不僅僅是在控制台中顯示網址。 </p> <p>//這是我的 html(這確實很基本,但我只想讓輸出正常工作)</p> <pre class="brush:php;toolbar:false;"><!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 src="catGif.js"> </script> </body> </html></pre> <p>//這是我的 JavaScript</p> <pre class="brush:php;toolbar:false;">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); } }</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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板