Json : 딕셔너리 { }와 리스트 [ ] 조합과 생김새가 비슷
API ( = 은행 창구) : 클라이언트가 요청( 타입 : GET, POST) ⇔ 서버가 답
1) GET : 데이터 조회(Read) ex) 영화 목록 조회
--> 요청 URL : http:// 서버 주소/ 창구이름?고객이 가지고 가는 데이터1&데이터2
ㄴ> ? : 전달할 데이터가 작성된다
ㄴ> & : 전달할 데이터가 더 있다
2) POST : 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 ex) 회원가입, 회원탈퇴, 비번 수정
--> 4주차에 배움!!
Ajax : 서버통신의 마법
--> 자바스크립트로 페이지 전환없이 서버에서 값을 받아올 수 있는 방법
--> JQuery를 임포트한 페이지에서만 동작 가능
--> 개발자 도구 > Console 에서
--> Ajax 기본 골격
ㄴ> response 는 다른 이름이어도 됨!!
> $.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){ ----------> let 구문, if 구문, for 구문 등등 쓰면 됨
console.log(response)
}
})
※ 코드 설명
▷ type: "GET" --> GET 방식으로 요청
▷ data: {} --> 요청하면서 함께 줄 데이터(GET 요청시엔 비워둠)
GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
http://naver.com?param=value¶m2=value2
POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다.
data: { param: 'value', param2: 'value2' },
퀴즈 1
서울 미세먼지 실시간 http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99
1. 반복문 사용해서 구 데이터 출력
> $.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){
let rows = response[ 'RealtimeCityAir' ] [ 'row' ]
for ( let i = 0; i < rows.length; i++ ) {
let gu_name = rows[ i ] [ 'MSRSTE_NM' ]
let gu_mise = rows[ i ] [ 'IDEX_MVL' ]
console.log(gu_name, gu_mise)
}
}
})
< 중구 91 종로구 96 ...................
2. 1에서 미세먼지가 70 미만 추출
> $.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){
let rows = response[ 'RealtimeCityAir' ] [ 'row' ]
for ( let i = 0; i < rows.length; i++ ) {
let gu_name = rows[ i ] [ 'MSRSTE_NM' ]
let gu_mise = rows[ i ] [ 'IDEX_MVL' ]
if (gu_mise < 70) {
console.log(gu_name, gu_mise)
}
}
}
})
< 강서구 66 양천구 60
3. 페이지에 입력되게 하기
1) 반응하는지 console 확인 --> object 뜸!
function q1() {
$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {},
success: function(response){
console.log(response)
}
})
}
2) 반복문 잘 들어왔는지 console 확인 --> 콘솔에 딕셔너리로 뜸!
function q1() {
$.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++) {
console.log(response)
}
}
})
}
3) 구 이름이랑 미세먼지 값 뜨는지 확인 --> 잘 뜸!
function q1() {
$.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 gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
console.log(gu_name, gu_mise)
}
}
})
}
4) html 잘 넣어지는지 console 확인 --> 잘 뜸
function q1() {
$.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 gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
let temp_html = `<li>${gu_name} : ${gu_mise}</li>`
console.log(temp_html)
}
}
})
}
5) 화면에 html 넣기
function q1() {
$.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 gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
let temp_html = `<li>${gu_name} : ${gu_mise}</li>`
$('#names-q1').append(temp_html)
}
}
})
}
6) 버튼 누를 때마다 지우고 적어주게 하기
<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 gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
let temp_html = `<li> ${gu_name} : ${gu_mise} </li>`
$('#names-q1').append(temp_html)
}
}
})
}
</script>
※ 부가 설명
▷ .empty( ) : 지우기(클릭할때마다 계속 추가되는거 방지)
▷ temp_html : html 만들기 ` `(백틱)으로 해야함!! 안에 이름 변경 시 $ { 이름 } 으로 해야함!!!
▷ $( ' # id ' ).append( temp_html ) : 추가하기
4. 3번에 미세먼지 값이 70 이상이면 글자색 레드로 주기
<style>
.bad {
color: red; -----> CSS로 글자색 레드
}
</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 gu_name = rows[i]['MSRSTE_NM']
let gu_mise = rows[i]['IDEX_MVL']
let temp_html = ``
if (gu_mise > 70) {
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>
※ 부가 설명
▷ let temp_html = ` `
if (gu_mise > 70) { temp_html = ` <li class = "bad" >${gu_name} : ${gu_mise} </li>` }
else { temp_html = `<li> ${gu_name} : ${gu_mise} </li>` }
ㄴ> 의미 : if 미세먼지 > 70 이면 bad 이름 설정된 <li>를 적고,
그게 아니라면 일반 <li>를 적어라!
퀴즈2
서울 따릉이 http://spartacodingclub.shop/sparta_api/seoulbike
1) 페이지에 보이게 하기
function q1() {
$('#names-q1').empty()
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulbike",
data: {},
success: function (response) {
let rows = response['getStationList']['row']
for(let i = 0; i < rows.length; i++) {
let name = rows[i]['stationName']
let rack_cnt = rows[i]['rackTotCnt']
let bike_cnt = rows[i]['parkingBikeTotCnt']
let temp_html = `<tr>
<td>${name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`
$('#names-q1').append(temp_html)
}
}
})
}
2) 바이크 수가 5 미만이면 빨간색 글자
.urgent {
color: red
}
function q1() {
$('#names-q1').empty()
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulbike",
data: {},
success: function (response) {
let rows = response['getStationList']['row']
for(let i = 0; i < rows.length; i++) {
let name = rows[i]['stationName']
let rack_cnt = rows[i]['rackTotCnt']
let bike_cnt = rows[i]['parkingBikeTotCnt']
let temp_html = ``
if (bike_cnt < 5) {
temp_html = `<tr class="urgent">
<td>${name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`
} else {
temp_html = `<tr>
<td>${name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`
}
$('#names-q1').append(temp_html)
}
}
})
}
퀴즈3
고양이이미지 https://api.thecatapi.com/v1/images/search --> 리스트 형태임
강아지이미지 https://api.thedogapi.com/v1/images/search
1) 반응하는지 console 확인 --> 잘 뜸 (0번째의 url 임을 알 수 있음)
function q1() {
$.ajax({
type: "GET",
url: "https://api.thecatapi.com/v1/images/search",
data: {},
success: function (response) {
console.log(response)
}
})
}
2) url이 잘 들어오는지 console 확인
function q1() {
$.ajax({
type: "GET",
url: "https://api.thecatapi.com/v1/images/search",
data: {},
success: function (response) {
console.log(response[0]['url'])
}
})
}
3) url 을 src로 변경
function q1() {
$.ajax({
type: "GET",
url: "https://api.thecatapi.com/v1/images/search",
data: {},
success: function (response) {
let imgurl = response[0]['url']
$("#img-cat").attr("src", imgurl);
}
})
}
※ 부가 설명
▷ 리스트 형식은 딕셔너리와 다르게 row 등등 없음
▷ 0번째 url 을 impurl 로 선언
▷ 이미지 url을 src로 변환 : $(' # id ').attr("src", 이미지url);
2주차 완주!!!!!
2주차가 1주차에 비해 좀 어려웠따...... 두번째 들을 때 더 이해하고 파악해보는걸로 해야겠다 ㅠㅠㅠㅠ
(강사 말론 2주차가 어렵고 3주차는 정말 재밌다고 했다 씐난당>< )
그래도 다행히 재미없는 어려움이 아니어서 잘 할 수 있었던 거 같움!!
3주차도 힘내서 화이팅!!!!!!!!!

'Python > Web_log' 카테고리의 다른 글
22.06.23(목) (0) | 2022.06.23 |
---|---|
22.06.04 (0) | 2022.06.23 |
22.06.21(화) (0) | 2022.06.22 |
22.06.20(월) (0) | 2022.06.21 |
22.06.16(목) (0) | 2022.06.17 |