$.ajax({ type: "GET", url: "여기에URL을입력", data: {}, success: function(response){ console.log(response) }})
script부분 함수를 실행할 부분에 넣는다
function q1() { $('#names-q1').empty() $.ajax({ type: "GET", url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99", data: {}, success: function(response){ let rows = response['RealtimeCityAir']['row'] for (let i = 0; i< rows.length; i++){ let name = rows[i]['MSRSTE_NM'] let mise = rows[i]['IDEX_MVL'] let temp_html = ` <li>${name} : ${mise}</li>` $('#names-q1').append(temp_html) } } }) }
url부분에 우리가 가져올 오픈 api를 넣는다
가져온 응답은 response에 담아서 가져오게 된다.
이것은 미세먼지 api이다.
url에 들어가면 json형태로 값이 저장되어있다

이렇게 있는데 우리는 그 중에서 구이름과 미세먼지 수치만 가져올 것이다.

변수를 하나 만들고 row안으로 들어간다
그리고 for문을 돌면서 구 이름과 미세먼지 수치를 가져와서
html을 append하여 붙이고 싶은 곳에 붙인다.
전체 코드
<!doctype html><html lang="ko"><head> <meta charset="UTF-8"> <title>jQuery 연습하고 가기!</title> <!-- jQuery를 import 합니다 --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <style type="text/css"> div.question-box { margin: 10px 0 20px 0; } </style> <script> function q1() { $('#names-q1').empty() $.ajax({ type: "GET", url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99", data: {}, success: function(response){ let rows = response['RealtimeCityAir']['row'] for (let i = 0; i< rows.length; i++){ let name = rows[i]['MSRSTE_NM'] let mise = rows[i]['IDEX_MVL'] let temp_html = ` <li>${name} : ${mise}</li>` $('#names-q1').append(temp_html) } } }) } </script></head><body> <h1>jQuery+Ajax의 조합을 연습하자!</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>
그러면

업데이트를 눌렀을때

이렇게 쭉 나오게 된다.
그럼 여기서 70이상 수치를 가진 곳은 빨간색으로 표시해보자
function q1() { $('#names-q1').empty() $.ajax({ type: "GET", url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99", data: {}, success: function(response){ let rows = response['RealtimeCityAir']['row'] for (let i = 0; i< rows.length; i++){ let name = rows[i]['MSRSTE_NM'] let mise = rows[i]['IDEX_MVL'] let temp_html = `` if (mise<70){ temp_html = ` <li>${name} : ${mise}</li>` } else{ temp_html = ` <li class="bad">${name} : ${mise}</li>` } $('#names-q1').append(temp_html) } } }) }
그러면 70이상인 곳에 class를 주어서 style을 바꿔주면 된다
728x90
'WEB > Java Script' 카테고리의 다른 글
[Java Script] async 비동기처리/ Callback과 콜백 지옥에 대해 알아보자! (0) | 2021.09.28 |
---|---|
[Java Script] 자바스크립트의 역사와 현재 그리고 미래 (0) | 2021.09.22 |
[Java Script] spread 함수 인자로 사용 / 배열의 원소를 모두 함수 인자로 넣고 싶을 때 (0) | 2021.04.24 |
[Java Script] rest / 특정값만 제외하고 가져온다/ 함수의 파라미터의 개수가 몇개일 지 모를 때 사용 (1) | 2021.04.24 |
[Java Script] spread / 객체와 배열의 값을 그대로 복사해서 새로운 객체와 배열을 만드는 법 (0) | 2021.04.24 |