☑️ 서버-클라이언트 통신 이해하기
✦ API는 은행 창구와 같은 것!
같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라
가져와야 하는 것 / 처리해주는 것이 다른 것처럼,
클라이언트가 요청 할 때에도, "타입"이라는 것이 존재
GET → 통상적으로! 데이터 조회(Read)를 요청할 때
예) 영화 목록 조회
POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
예) 회원가입, 회원탈퇴, 비밀번호 수정
✦ URL
https://movie.naver.com/movie/bi/mi/basic.nhn?code=161967
✦ code라는 이름으로 영화번호를 주자는 것은 누가 하나?
→ 프론트엔드 개발자와 백엔드 개발자가 미리 정해둔 약속
␣
☑️ Ajax
⭐️ Ajax는 jQuery를 임포트한 페이지에서만 동작 가능 ⭐️
Uncaught TypeError: $.ajax is not a function
→ ajax라는 게 없다는 뜻
✦ Ajax 기본 골격
$.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){
console.log(response)
}
})
✦ $.ajax 코드 설명
- type: "GET" → GET 방식으로 요청한다.
- url: 요청할 url
- data: 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두기)
* GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져간다.
http://naver.com?param=value¶m2=value2
* POST 요청은, data : {} 에 넣어서 데이터를 가져간다.
data: { param: 'value', param2: 'value2' },
⎯ success: 성공하면, response 값에 서버의 결과 값을 담아서 함수를 실행한다.
success: function(response){
console.log(response)
}
// 서버에서 준 결과를 response라는 변수에 담음
$.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)
}
}
})
$.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']
if(gu_mise < 70) {
console.log(gu_name,gu_mise)
}
}
}
})
☑️ Ajax Qiuz_1
<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>
<!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;
}
</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 > 55) {
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>
</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 Qiuz_2
✽ 과정
<script>
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 station_name = rows[i]['stationName']
let tripod = rows[i]['rackTotCnt']
let parking_bike = rows[i]['parkingBikeTotCnt']
let temp_html = `<tr>
<td>${station_name}</td>
<td>${tripod}</td>
<td>${parking_bike}</td>
</tr>`
$('#names-q1').append(temp_html)
}
}
})
}
</script>
<style type="text/css">
div.question-box {
margin: 10px 0 20px 0;
}
table {
border: 1px solid;
border-collapse: collapse;
}
td,
th {
padding: 10px;
border: 1px solid;
}
.redpoint {
color: red;
font-weight: bold;
}
</style>
<script>
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 station_name = rows[i]['stationName']
let tripod = rows[i]['rackTotCnt']
let parking_bike = rows[i]['parkingBikeTotCnt']
let temp_html = ``
if (parking_bike < 5) {
temp_html = `<tr class = "redpoint">
<td>${station_name}</td>
<td>${tripod}</td>
<td>${parking_bike}</td>
</tr>`
} else {
temp_html = `<tr>
<td>${station_name}</td>
<td>${tripod}</td>
<td>${parking_bike}</td>
</tr>`
}
$('#names-q1').append(temp_html)
}
}
})
}
</script>
<!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;
}
table {
border: 1px solid;
border-collapse: collapse;
}
td,
th {
padding: 10px;
border: 1px solid;
}
.redpoint {
color: red;
font-weight: bold;
}
</style>
<script>
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 station_name = rows[i]['stationName']
let tripod = rows[i]['rackTotCnt']
let parking_bike = rows[i]['parkingBikeTotCnt']
let temp_html = ``
if (parking_bike < 5) {
temp_html = `<tr class = "redpoint">
<td>${station_name}</td>
<td>${tripod}</td>
<td>${parking_bike}</td>
</tr>`
} else {
temp_html = `<tr>
<td>${station_name}</td>
<td>${tripod}</td>
<td>${parking_bike}</td>
</tr>`
}
$('#names-q1').append(temp_html)
}
}
})
}
</script>
</head>
<body>
<h1>jQuery + Ajax의 조합을 연습하자!</h1>
<hr/>
<div class="question-box">
<h2>2. 서울시 OpenAPI(실시간 따릉기 현황)를 이용하기</h2>
<p>모든 위치의 따릉이 현황을 보여주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">업데이트</button>
<table>
<thead>
<tr>
<td>거치대 위치</td>
<td>거치대 수</td>
<td>현재 거치된 따릉이 수</td>
</tr>
</thead>
<tbody id="names-q1"> </tbody>
</table>
</div>
</body>
</html>
␣
☑️ Ajax Qiuz_3
✽ 과정
<script>
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)
}
})
}
</script>
📌 jquery img src 변경하기
$('#id-name').attr('src', '변경할url');
<!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;
}
div.question-box > div {
margin-top: 30px;
}
</style>
<script>
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);
}
})
}
</script>
</head>
<body>
<h1>JQuery+Ajax의 조합을 연습하자!</h1>
<hr/>
<div class="question-box">
<h2>3. 랜덤 고양이 사진 API를 이용하기</h2>
<p>예쁜 고양이 사진을 보여주세요</p>
<p>업데이트 버튼을 누를 때마다 지웠다 새로 씌여져야 합니다.</p>
<button onclick="q1()">고양이를 보자</button>
<div>
<img id="img-cat" width="300" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/>
</div>
</div>
</body>
</html>
응용머리 안 돌아가고 어렵고 때려치고 싶다....