2024. 1. 23. 08:23ㆍ스파르타_부트캠프/웹개발
강의 자료
2주차
09. Fetch로 요청 보내기
fetch.html 생성 및 script 페이지에 다음 코드 추가
<script>
fetch("http://spartacodingclub.shop/sparta_api/seoulair") // 이 URL로 웹 통신을 요청한다. 괄호 안에 다른 것이 없다면 GET!
.then(res => res.json()) // 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 한다
.then(data => {
console.log(data) // 개발자 도구에 찍어보기
}) // JSON 형태로 바뀐 데이터를 data라는 이름으로 붙여 사용한다
</script>
해당 url은 미세먼지 OpenAPI 주소이며, 개발자도구에서 로그를 확인해본 결과 다음과 같이 log가 출력된다.
10. Fetch 데이터 처리하기
위의 출력 결과를 확인하여 json의 Key를 확인 후 다음과 같이 코드를 작성하여 원하는 데이터를 출력해본다.
<script>
fetch("http://spartacodingclub.shop/sparta_api/seoulair") // 이 URL로 웹 통신을 요청한다. 괄호 안에 다른 것이 없다면 GET!
.then(res => res.json()) // 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 한다
.then(data => {
// console.log(data) // 개발자 도구에 찍어보기
console.log('RealtimeCityAir, row, 0 | result >>');
console.log(data['RealtimeCityAir']['row'][0]);
}) // JSON 형태로 바뀐 데이터를 data라는 이름으로 붙여 사용한다
</script>
모든 row MSRTRE_NM, IDEX_MVL 키 값만 출력하려면 다음과 같이 forEach 루프를 사용한다.
<script>
fetch("http://spartacodingclub.shop/sparta_api/seoulair") // 기본 요청(GET)
.then(res => res.json()) // 요청해서 받은 데이터를 JSON화
.then(data => { // JSON화 한 데이터를 다시 data로 이름짓기
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
// 미세먼지 데이터 리스트의 길이만큼 반복해서 하나씩 개발자 도구에서 보기
// 구의 이름, 미세먼지 수치 값을 개발자 도구에서 찍어보기
console.log(a['MSRSTE_NM'], a['IDEX_MVL'])
})
})
</script>
다음과 같이 해당 key값에 해당하는 로그가 출력된다.
11. Fetch 연습하기(1)
기본 골격 코드를 가져온 후 실행하면 다음과 같다.
내용을 진행하기 위해 q1 함수에 다음과 같이 코드를 추가한다.
<script>
function q1() {
// 여기에 코드를 입력하세요
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
let rows = data['RealtimeCityAir']['row']
$('#names-q1').empty()
rows.forEach((row) => {
let gu_name = row['MSRSTE_NM']
let gu_mise = row['IDEX_MVL']
console.log(gu_name, gu_mise)
let temp_html = `<li>${gu_name} : ${gu_mise}</li>`
$('#names-q1').append(temp_html)
})
})
}
</script>
url에서 json을 읽어온 후 data['RealtieCityAir']['row']의 rows를 읽어온다. 그 후 jquery id를 조회를 사용하여, name_q1을 가져온 후 해당 태그 하위의 값을 제거한다.
이 후 forEach에서 각 row의 key인 'MSRESTR_NM', 'IDEX_MVL'을 참조하여 동적으로 li 태그를 사용한 코드를 생성하여 name-q1에 append 한다.
결과는 다음과 같다.
12. Fetch 연습하기(2)
위의 코드에서 미세먼지가 40이 넘는 페이지만 빨간색으로 표시한다.
코드는 다음과 같다.
<style>
div.question-box {
margin: 10px 0 20px 0;
}
.bad {
color: red;
}
</style>
<script>
function q1() {
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then((response) => response.json()).the범n((data) => {
$('#names-q1').empty()
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
let gu_name = a['MSRSTE_NM']
let gu_mise = a['IDEX_MVL']
let temp_html = ``
if (gu_mise > 40) {
temp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>`
} else {
temp_html = `<li>${gu_name} : ${gu_mise}</li>`
}
$('#names-q1').append(temp_html)
});
})
}
</script>
css에 색상정보를 저장하는 bad를 추가하고 li 태그 class에 bad를 적용한다.
javascript에서는 gu_mise에 조건문을 적용하며 40 이상인 경우에만 class="bad" 를 적용한다.
결과는 다음과 같다.
13. 데일리모토 명언 기능 적용
motto.html에 명언 기능을 적용한다. URL에서 명언 json을 가져온 후 하단에 다음과 같이 표시해준다.
footer의 p 태그에 id를 부여한다.
<div class="footer">
<p id="quoteAuthor">- 작자 미상 -</p>
<p id="quoteContent">멋진 명언입니다. 아이스크림을 먹으면 행복해져요.</p>
</div>
jquery를 사용하기 위해 다음을 추가한다.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
script에서 다음 코드를 추가하여 fetch된 url의 json을 가져온 후 footer의 각 id에 적용한다.
<script>
$(document).ready(function renderQuote() {
let url = `https://api.quotable.io/random`;
fetch(url)
.then((res) => res.json())
.then((data) => {
let author = data["author"]
let content = data["content"];
let author2 = `- ${author} -`
let content2 = `" ${content} "`
$("#quoteAuthor").text(author2);
$("#quoteContent").text(content2);
});
})
</script>
다음과 같이 명언이 출력되는 것을 확인할 수 있다.
14. Homework
다음 OpenAPI 링크에서 json을 가져온 후 실시간 서울 날씨를 적용한다.
http://spartacodingclub.shop/sparta_api/weather/seoul
결과는 다음과 같이 나와야한다.
다음과 같이 html에 weatherTemp id를 추가한 후
<div class="weather">
<img src="https://ssl.gstatic.com/onebox/weather/64/partly_cloudy.png" id="weather-icon">
<p id="weatherTemp">날씨 맑음, 20ºC</p>
</div>
다음 javascript 함수를 추가하여 온도 값을 가져온 후 weatherTemp에 반영한다.
<script>
$(document).ready(function renderWeather() {
let weather_url = "http://spartacodingclub.shop/sparta_api/weather/seoul";
fetch(weather_url)
.then(res => res.json())
.then(data => {
//console.log(data);
let temp = data["temp"]
let temp_str = `${temp} ºC`
$("#weatherTemp").text(temp_str);
})
})
</script>
다음과 같이 현재 서울날씨가 반영되었다. (오늘 엄청 추웠는데 온도가 -11도인 것을 보니 정확한 데이터이다... 해당 API가 데이터를 훌륭히 반환하는 것을 알 수 있다...)
'스파르타_부트캠프 > 웹개발' 카테고리의 다른 글
ChatGPT 웹개발 진행노트 - 6일차 (1) | 2024.02.02 |
---|---|
ChatGPT 웹개발 진행노트 - 5일차 (0) | 2024.01.25 |
ChatGPT 웹개발 진행노트 - 3일차 (0) | 2024.01.22 |
ChatGPT 웹개발 진행노트 - 2일차 (0) | 2024.01.20 |
ChatGPT 웹개발 진행노트 - 1일차 (0) | 2024.01.19 |