Fetch 통신의 결과 값을 이용해보기 (OpenAPI 이용)

fetch("http://spartacodingclub.shop/sparta_api/seoulair")
.then(res => res.json())
.then(data => {
console.log(data['RealtimeCityAir']['row'][0]);
})
반복문으로 구 데이터를 출력해보기

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)
})
})
구 데이터에서 구 이름, 미세먼지 수치를 골라내어 출력하기

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'])
})
})
미세먼지 데이터 찍어보기
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
console.log(a['MSRSTE_NM'], a['IDEX_MVL'])
})
})
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Fetch 시작하기</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function hey() {
let url = 'http://spartacodingclub.shop/sparta_api/seoulair';
fetch(url).then(res => res.json()).then(data => {
let rows = data['RealtimeCityAir']['row'];
rows.forEach(a => {
let gu_name = a['MSRSTE_NM'];
let gu_mise = a['IDEX_MVL'];
console.log(gu_name, gu_mise);
});
})
}
</script>
</head>
<body>
<button onclick="hey()">fetch 연습!</button>
</body>
</html>
서울시 OpenAPI(실시간 미세먼지)를 이용하기
http://spartacodingclub.shop/sparta_api/seoulair // 미세먼지 OpenAPI
뼈대에 fetch 기본 골격을 붙여본다.
<script>
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
console.log(data)
})
</script>
console.log()로 데이터 가져오기
<script>
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then(res => res.json()).then(data => {
console.log(data)
})
</script>
- forEach문을 사용.
- forEach문의 만듬새 오타에 주의.
- 구 이름, 미세먼지 수치와 관련된 데이터를 뽑아서 console에서 확인한다.
웹에 붙일 temp_html 제작
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
let gu_name = a['MSRSTE_NM']
let gu_mise = a['IDEX_MVL']
console.log(gu_name, gu_mise)
let temp_html = `<li>중구 : 82</li>`
$('#names-q1').append(temp_html)
})
가져올 데이터를 temp_html에 넣기
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
let gu_name = a[]
let gu_mise = a[]
console.log(gu_name, gu_mise)
let temp_html = `<li>${gu_name} : ${gu_mise}</li>`
$('#names-q1').append(temp_html)
})
처음에 보이는 정보는 지워준다.
let rows = data['RealtimeCityAir']['row']
$('#names-q1').empty()
rows.forEach((a) => {
let gu_name = a[]
let gu_mise = a[]
console.log(gu_name, gu_mise)
let temp_html = `<li>${gu_name} : ${gu_mise}</li>`
$('#names-q1').append(temp_html)
})
[완성코드] fetch
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>미세먼지 API로Fetch 연습하고 가기!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}
</style>
<script>
function q1() {
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then((response) => response.json()).then((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 = `<li>${gu_name} : ${gu_mise}</li>`
$('#names-q1').append(temp_html)
});
})
}
</script>
</head>
<body>
<h1>Fetch 연습하자!</h1>
<hr/>
<div class="question-box">
<h2>1. 서울시 OpenAPI(실시간 미세먼지 상태)를 이용하기</h2>
<p>모든 구의 미세먼지를 표기해주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">업데이트</button>
<ul id="names-q1">
<li>중구 : 82</li>
<li>종로구 : 87</li>
<li>용산구 : 84</li>
<li>은평구 : 82</li>
</ul>
</div>
</body>
</html>
미세먼지 수치가 40이상인 곳이 빨갛게 표현할 경우
<style>
.bad {
color: red;
}
</style>
<script>
function q1() {
fetch("http://spartacodingclub.shop/sparta_api/seoulair").then((response) => response.json()).then((data) => {
$('#names-q1').empty()
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
let gu_name = a[]
let gu_mise = a[]
let temp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>` //일단 빨간색으로 색깔적용
$('#names-q1').append(temp_html)
})
}
</script>
gu_mise 값을 확인하는 조건문을 달아준다.
<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()).then((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) { //미세먼지가 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>
Fetch 적용

- script 태그안에 새로운 $(document).ready(function() { ... }) 함수 작성
- fetch 함수를 사용하여 주어진 URL에서 데이터를 가져오기
- .then(res => res.json()) 반환 된 응답(response)내용을 JSON 형식으로 만들기
- .then(data => { ... }) JSON 데이터를 가져온 후
- temperature 값을 변수에 담는다!
- 선택자 선택 후 IDEX_NM의 값을 문자열로 삽입
$(document).ready(function () {
let url = "http://spartacodingclub.shop/sparta_api/seoulair";
fetch(url).then(res => res.json()).then(data => { // 해당 URL에서 데이터를 가져옵니다. fetch() 함수는 Promise를 반환하며, 이를 통해 비동기적으로 데이터를 처리합니다.
let mise = data['RealtimeCityAir']['row'][0]['IDEX_NM'] // JSON 데이터의 특정 키(여기서는 'RealtimeCityAir')에 해당하는 값을 가져옵니다.
$('#msg').text(mise)
})
})
'웹개발 기초정리(프엔)' 카테고리의 다른 글
URL이란? (0) | 2024.07.09 |
---|---|
데이터 베이스란? (0) | 2024.07.08 |
Fetch 정리. 1 (1) | 2024.07.05 |
JQuery 기초정리. 2 (1) | 2024.07.05 |
JQuery기초 정리. 1 (0) | 2024.07.02 |