gpt4 book ai didi

javascript - 如何在从 API 获取数据时添加加载动画? Vanilla js

转载 作者:行者123 更新时间:2023-11-30 09:17:51 24 4
gpt4 key购买 nike

我在这里尝试了很多答案,但我找到的所有答案,人们都在使用 jquery、ajax、react 或类似的东西。我想要一个纯 javascript(vanilla js)的答案。

const movieApiMovies = () => {
fetch(movieApi_url + "movies/")
.then(response => response.json())
.then(function (data) {
let result = `<h2> Movies I've watched! </h2>`;
data.forEach((movie) => {
const {id, name, year, note_imdb, genre, duration} = movie;
result +=
`<div>
<h5> Movie ID: ${id} </h5>
<ul>
<li>Movie name: ${name}</li>
<li>Movie year: ${year}</li>
<li>Movie note on IMDB: ${note_imdb}</li>
<li>Movie Genre: ${genre}</li>
<li>Movie duration: ${duration}</li>
</ul>
</div>`;
document.getElementById('movieResult').innerHTML = result;
})
})
};

我有一个动画,它在这个 Div 元素上。

<div class="boxLoading"></div>

我有一个可以调用所有内容的按钮。

<div id="button1">
<button class="button" id="moviesfromapi"onclick="movieApiMovies ()">Display</button>
</div>

最佳答案

在调用之前添加加载器,并在收到结果后删除,如下所示

const movieApiMovies = () => {
let loader = `<div class="boxLoading"></div>`;
document.getElementById('movieResult').innerHTML = loader;
fetch(movieApi_url + "movies/")
.then(response => response.json())
.then(function (data) {
let result = `<h2> Movies I've watched! </h2>`;
data.forEach((movie) => {
const {id, name, year, note_imdb, genre, duration} = movie;
result +=
`<div>
<h5> Movie ID: ${id} </h5>
<ul>
<li>Movie name: ${name}</li>
<li>Movie year: ${year}</li>
<li>Movie note on IMDB: ${note_imdb}</li>
<li>Movie Genre: ${genre}</li>
<li>Movie duration: ${duration}</li>
</ul>
</div>`;
document.getElementById('movieResult').innerHTML = result;
})
})
};

关于javascript - 如何在从 API 获取数据时添加加载动画? Vanilla js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53799108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com