从API获取数据时如何添加加载动画?香草js

时间:2018-12-16 03:06:24

标签: javascript css api promise loading

我在这里尝试了很多答案,但是我发现所有答案,人们正在使用jquery,ajax,react或类似方法。我想要一个纯JavaScript(香草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>

1 个答案:

答案 0 :(得分:1)

在调用前添加加载程序,并在收到结果后将其删除,如下所示

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;
        })
    })
};