Fetch를 쓰면서 jQuery를 사용할 것이기 때문에 jQuery를 임포트한 페이지에서만 동작한다.
즉, http://google.com/ 과 같은 화면에서 [개발자도구]를 열면, jQuery가 임포트 되어있지 않기 때문에 아래와 같은 에러가 뜬다. Uncaught TypeError: $ is not a function → jQuery 라는 게 없다는 뜻
Fetch 연습 prac2.html
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Fetch 시작하기</title>
<script>
</script>
</head>
<body>
Fetch 연습을 위한 페이지
</body>
</html>
✅ Fetch 기본 골격
<script>
fetch("여기에 URL을 입력").then(res => res.json()).then(data => {
console.log(data)
})
</script>
fetch("여기에 URL을 입력") // 이 URL로 웹 통신을 요청한다. 괄호 안에 다른 것이 없다면 GET!
⛔ GET 요청은 url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
http://naver.com?param=value¶m2=value2
⛔ POST 요청은 data : {} 에 넣어서 데이터를 가져갑니다.
data: { param: 'value', param2: 'value2' },
.then(res => res.json()) // 통신 요청을 받은 데이터는 res라는 이름으로 JSON화 한다.
.then(data => {
console.log(data) // 개발자 도구에 찍어보기
}) // JSON 형태로 바뀐 데이터를 data라는 이름으로 붙여 사용한다.
✅ Fetch 코드 설명
- fetch("여기에 URL을 입력") ← URL로 웹 통신 요청을 보낼 거야!
- ← 괄호 안에 URL밖에 들어있지 않다면 기본상태인 GET!
- .then() ← 통신 요청을 받은 다음 이렇게 할 거야!
- res ⇒ res.json()
- ← 통신 요청을 받은 데이터는 res 라는 이름을 붙일 거야(변경 가능)
- ← res는 JSON 형태로 바꿔서 조작할 수 있게 할 거야!
- .then(data ⇒ {}) ←JSON 형태로 바뀐 데이터를 data 라는 이름으로 붙일거야
<script>
fetch("http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99").then(res => res.json()).then(data => {
console.log(data['RealtimeCityAir']['row'][0])
})
</script>
<script>
fetch("http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99").then(res => res.json()).then(data => {
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
console.log(a['MSRSTE_NM'])
})
})
</script>
<script>
fetch("http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99").then(res => res.json()).then(data => {
let rows = data['RealtimeCityAir']['row']
rows.forEach((a) => {
console.log(a['MSRSTE_NM'],a['IDEX_MVL'])
})
})
</script>
'Javascript' 카테고리의 다른 글
fetch 반복문 / 조건문 (0) | 2023.07.13 |
---|---|
fetch / forEach / $('#id').append(temp_html) (0) | 2023.07.12 |
서버→클라이언트: "JSON" (0) | 2023.07.12 |
JQuery / $('#id').append(temp_html) (0) | 2023.07.12 |
JQuery 반복문 / 조건문 (0) | 2023.07.11 |