Front-End/4. jQuery

Ex07_비동기 통신.html

이뮨01 2023. 6. 22. 21:07

새로고침을 하지 않아도 데이터가 로드되는 비동기 통신을 배우다.


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="result-area">

    </div>
    <button id="req-button">
        데이터 요청
    </button>
    <!-- jQuery 파일 불러오기 -->
    <script src="./js/jquery-3.7.0.js"></script>
    <script>
        // 데이터요청 버튼 클릭 시, 동작하는 이벤트 적용해보기
        $("#req-button").on("click", () => {
            // alert("클릭")

            let movieURL = "https://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230621"

            // $.ajax() : 비동기 통신을 지원하는 함수
            $.ajax({
                url: movieURL,
                success: (result) => {
                    alert("요청성공!")
                    // console.log(result);
                    // console.log(result.boxOfficeResult);
                    // console.log(result.boxOfficeResult.dailyBoxOfficeList);

                    let movieList = result.boxOfficeResult.dailyBoxOfficeList;
                    
                    // 박스오피스 순위, 영화이름, 개봉일을 콘솔창에 출력
                    $('div').append(`<table border="1px"></table>`)
                    $('table').append(
                        `<tr>
                        <th>순위</th>
                        <th>영화명</th>
                        <th>개봉일</th>
                        </tr>`)
                    for (let i = 0; i < movieList.length; i++) {
                        // console.log(movieList[i].rank,'/',movieList[i].movieNm,'/',movieList[i].openDt)  
                        // console.log(`${movieList[i].rank}.${movieList[i].movieNm}(${movieList[i].openDt})`)

                        $('table').append(`<tr align = "center">
                            <td>${movieList[i].rank}</td>
                            <td>${movieList[i].movieNm}</td>
                            <td>${movieList[i].openDt}</td>
                            </tr>`)

                    };


                },
                error: () => {
                    alert("요청실패..")
                }
            });
        })

    </script>
</body>

</html>

결과

동시에 여러가지 작업을 진행할 수 있고, 새로고침을 하지 않아도 웹 페이지 일부분에서 새로운 데이터가 로드 되는 비동기식 통신을 배우다. 비동기식 통신을 위한 제이쿼리 함수는 $.ajax( ) 이다.

이 함수를 실행시키기 위해서는 객체 key값으로 url, success가 필요하다. url의 value에는 오픈 api 링크 주소를 넣고 success에는 요청이 정상적으로 성공되면 실행될 로직을 적으면 된다. 나는 버튼을 클릭하면 2023-06-21 기준으로 일일 영화 순위를 표(table)로 만들어주는 로직을 작성했다.