본문 바로가기

Web_Project

[Jquery + Fetch] 버튼 누르면, 다음 영화 리뷰가 나오게 하는 방법

서버로부터 데이터를 받아온 데이터를 가공

다음 버튼 누르면, 다음 영화 리뷰가 보이게

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <title>띵동코딩-Fetch 연습</title>
        <style>
            .wrap {
                width: 300px;
                margin: auto;
            }

            .wrap > h1 {
                text-align: center;
            }

            .wrap > button {
                display: block;
                margin: auto;
                margin-bottom: 30px;
            }
        </style>
        <script>
            let cnt = 0;
            function movieReviews() {
                let url = 'http://spartacodingclub.shop/post';
                fetch(url)
                    .then((res) => res.json())
                    .then((data) => {
                        let rows = data['articles'];

                        let image = rows[cnt]['image'];
                        let title = rows[cnt]['title'];
                        let comment = rows[cnt]['comment'];

                        $('#moviesPic').attr('src', image);
                        $('#movieTitle').text(title);
                        $('#movieComment').text(comment);

                        cnt = cnt + 1;
                    });
            }
        </script>
    </head>

    <body>
        <div class="wrap">
            <h1>영화 버킷 리스트</h1>
            <button onclick="movieReviews()">다음</button>
            <div>
                <img id="moviesPic" width="300" src="" />
                <h2 id="movieTitle"></h2>
                <div id="movieComment"></div>
            </div>
        </div>
    </body>
</html>