Language/JavaScript

[Javascript] AJAX를 이용한 날짜 별 흥행 영화 출력하기

gangintheremark 2023. 7. 12. 20:01
728x90

AJAX 통신을 이용하여 yyyymmdd 형태로 날짜를 입력하면 해당 날짜의 영화 TOP 10 에 대한 순위, 제목, 개봉일을 출력해보자. 

        var httpRequest = null;
        function req() {
            // XMLHttpRequest 객체 생성
            httpRequest = new XMLHttpRequest();

            // 응답 시 처리하는 콜백함수 설정
            httpRequest.onreadystatechange = responseFunc;

            // 요청정보 설정
            var date = document.querySelector("#date").value;
            var url = `https://www.kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=3d430a039fb1bae3fe5f0bc48df64e46&targetDt=${date}`;
            httpRequest.open("get", url, true); // 요청방식 : GET, 비동기처리

            // 요청하기
            httpRequest.send(null); // GET 방식이면 null 지정
        }
        function responseFunc() {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                var str = httpRequest.responseText;
                var json = JSON.parse(str);

                // 배열일 경우
                var dailyBoxOfficeList = json.boxOfficeResult.dailyBoxOfficeList;
                var table = `
                    <table>
                        <tr>
                            <th> 순위 </th>
                            <th> 제목 </th>
                            <th> 개봉일 </th>
                        </tr>`;
                for (var daily of dailyBoxOfficeList) {
                    table += `<tr>
                        <td> ${daily.rank} </td>
                        <td> ${daily.movieNm} </td>
                        <td> ${daily.openDt} </td>
                        </tr>`;
                }
                table += `</table>`;
                document.querySelector("#result").innerHTML = table;
            }
        }

코드 실행결과

728x90