course/spartacoding
[웹개발 종합반] 2주차 (3) Ajax
hjkim0502
2021. 10. 29. 19:25
- Ajax는 jQuery가 import 되어 있는 페이지에서만 작동
-
Ajax 기본 골격 및 설명$.ajax({ type: "GET", // GET 방식으로 요청한다. url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99", data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요) success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음 console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성 } })
-
모든 구 이름과 그곳의 미세먼지 값 (70미만) 출력$.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 guName = rows[i]['MSRSTE_NM'] let guMise = rows[i]['IDEX_MVL'] if (guMise < 70) { console.log(guName, guMise) } } } })
-
ajax 연습하기 - 서울시 미세먼지 API<!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; } .bad { color: red; font-weight: bold; } </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 guName = rows[i]['MSRSTE_NM'] let guMise = rows[i]['IDEX_MVL'] let temp_html = `` if (guMise > 50) { temp_html = `<li class="bad">${guName} : ${guMise}</li>` } else { temp_html = `<li>${guName} : ${guMise}</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>
- 업데이트 버튼 클릭마다 데이터가 추가되므로 ajax 호출 전에 empty 함수 사용
- 조건문 사용해 미세먼지 50 초과만 styling