<!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">
<title>Promise Chain 방식</title>
</head>
<body>
<button type="button" id="btn">데이터 가져오기</button>
<ul id="ul"></ul>
<script>
document.getElementById('btn').addEventListener('click',()=>{
// fetch('https://jsonplaceholder.typicode.com/todos/1') //데이터 가져와서
// .then(resp => resp.json()) //1. 매개변수 resp에 json형식으로 데이터를 넣고 리턴
// .then(json => console.log(json)); //콘솔에 찍어라
// .catch(err=> console.log(err)); //실패시
// .then(resp => resp.text()) //2. 매개변수 resp에 text형식으로 데이터를 넣고 리턴
// .then(text => console.log(text)); //콘솔에 찍어라
//받아온 json객체를 화면에 li로 출력해보기
.then(resp => resp.json())
.then(json => printData(json)) //성공시
.catch(err=> console.log(err)); //실패시
})
//화면에 li로 출력하는 함수
let str=" ";
function printData(object){ // object = json객체
for(const o in object){
str += `<li>${o}:${object[o]}</li>`;
}
document.getElementById('ul').innerHTML = str;
}
</script>
<!-- <script>
// 1~5번 데이터까지 화면에 출력
document.getElementById('btn').addEventListener('click',()=>{
//1번 데이터
for(let i=1; i<=5; i++) {
fetch(`https://jsonplaceholder.typicode.com/todos/${i}`)
.then(resp => resp.json())
.then(json => printData(json));
}
})
let str1="";
//화면에 li로 출력하는 함수
function printData(object){ // object = json객체
for(const o in object){
str1 += `<li>${o}:${object[o]}</li>`;
}
document.getElementById('ul').innerHTML = str1;
}
</script> -->
</body>
</html>
'HTML.CSS.JS > JS' 카테고리의 다른 글
[JS] day13_fetch json데이터 가져와서 원하는 모양으로 출력하기 (0) | 2023.04.20 |
---|---|
[JS] day13_non_standard 비표준 속성 (0) | 2023.04.20 |
[JS] day13_async_await 데이터 불러오기 (0) | 2023.04.20 |
[JS] 구구단 ( 문제 출력 -> 맞추기 -> 결과 출력 ) (0) | 2023.04.20 |
[JS] popup 팝업창 (0) | 2023.04.20 |