프로그래밍 언어와 기술/JavaScript

[JavaScript] 실습 - fetch, 반복문 사용해서 li에 값 채우기

tero1115 2023. 7. 12. 17:36

https://jsonplaceholder.typicode.com/posts/

    <script>
        fetch("https://jsonplaceholder.typicode.com/posts/")
        .then((response) => response.json())
        .then((result) => {
            // forEach 또는 for 써서 titleList에 제목 li 넣기

            // for
            for (let i = 0; i < result.length; i++) {
                document.querySelector("#titleList").insertAdjacentHTML(
                    "beforeend",
                    `<li>${result[i].title}</li>`
                );
            }

            // forEach
            result.forEach((value) => {
                const tempLi = document.createElement("li");
                tempLi.innerText = value.title; 
                titleList.appendChild(tempLi);  
            });
        });
    </script>

 

 

 


http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230707 

<body>
    <ul id="movieList"></ul>    
    <script>
        fetch("http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20230707")
        .then(r => r.json())
        .then((result) => {
            // console.log(result)
            // console.log(result.boxOfficeResult.dailyBoxOfficeList);
            result.boxOfficeResult.dailyBoxOfficeList.forEach((value) => {
                document.querySelector("#movieList").insertAdjacentHTML(
                    "beforeend",
                    `<li>순위 : ${value.rank} / 제목 : ${value.movieNm}</li>`
                )
            });
        })
    </script>
</body>