서버-클라이언트 통신 이해하기
1. 서버 -> 클라이언트 : "JSON"
key : value 로 이루어져 있으며 자료형 Dictionary와 유사
2. 클라이언트 -> 서버 : GET 요청
클라이언트가 서버에 요청 할 때에 "타입"이라는 것이 존재
- GET -> 통상적으로 데이터 조회(read)를 요청 할 때
- POST -> 통상적으로 데이터 생성(creat), 변경(update), 삭제(delete) 요청 할 때 ex) 회원가입, 회원탈퇴 등
GET 방식
? : 이 뒤부터 전달할 데이터가 작성된다는 의미
& : 전달할 데이터가 더 있다
1) https://movie.naver.com/movie/bi/mi/basic.nhn?code=161967
서버주소 : https://movie.naver.com/movie/bi/mi/basic.nhn
영화정보(전달할 데이터) : code=161967
-> 여기서 코드 정보는 프론트 엔드 개발자와 백엔드 개발자가 미리 정해둔 약속 같은 것
2) google.com/search?q=아이폰&sourceid=chrome&ie=UTF-8
서버주소 : google.com/search
검색어 (q) : 아이폰
브라우저 정보 : sourceid=chrome
인코딩 정보 : ie=UTF-8
Ajax
Ajax는 jQuery를 임포트한 페이지에서만 동작 가능
Ajax 기본 골격
$.ajax({
type: "GET", // GET 방식으로 요청한다.
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})
//
success: function(response) // 성공하면, response 값에 서버의 결과 값을 담아서 함수를 실행
GET 방식은 url: " "
POST 방식은 data: { }
연습하기 1
- 모든 구의 구 이름, 미세먼지 값을 콘솔창에 표시
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
data: {},
success: function (response) {
let mise_list = response['RealtimeCityAir']['row'];
for (let i = 0; i < mise_list.length; i++) {
let mise = mise_list[i];
let gu_name = mise['MSRSTE_NM'];
let gu_mise = mise['IDEX_MVL'];
console.log(gu_name, gu_mise);
}
}
});
- 업데이트 버튼을 누르면 현재의 미세먼지 정보를 가져와 화면에 표시
<script>
function q1() {
$('#names-q1').empty();
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulair",
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>
</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">
</ul>
</div>
</body>
</html>
$('#names-q1').append(temp_html);
names-q1라고 지칭된 <ul>에 temp_html(<li>${gu_name} : ${gu_mise}</li>)을 삽입(append)한다
- 미세먼지 수치가 70이상인 곳은 빨간색으로 표시
<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://spartacodingclub.shop/sparta_api/seoulair",
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 = ``으로 ``안을 빈칸으로 만든후 조건문을 이용해 코드를 작성
미세먼지 수치가 70이상 일때의 <li>를 bad로 지칭
<style>에 bad를 color : red 로 css
$('#names-q1').empty(); 를 $.ajax위에 넣어 names-q1이 버튼을 누르기 전까지 없는 상태로 만든다
연습하기 2
- 따릉이가 5대 미만인 곳은 빨간색으로 표시
<style type="text/css">
.urgent {
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 name = rows[i]['stationName'];
let rack = rows[i]['rackTotCnt'];
let bike = rows[i]['parkingBikeTotCnt'];
let temp_html = '';
if (bike_cnt < 5) {
temp_html = `<tr class="urgent">
<td>${name}</td>
<td>${rack}</td>
<td>${bike}</td>
</tr>`
} else {
temp_html = `<tr>
<td>${name}</td>
<td>${rack}</td>
<td>${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>
연습하기 3
- 이미지, 텍스트 바꾸기
이미지 바꾸기 : $('#아이디값').attr('src', 이미지URL) -> 지칭된 id의 src 에 해당 이미지url을 넣는다
텍스트 바꾸기 : $('#아이디값').text('바꾸고 싶은 텍스트')
<script>
function q1() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rtan",
data: {},
success: function (response) {
let url = response['url']
let msg = response['msg']
$('#img-rtan').attr('src',url)
$('#text-rtan').text(msg)
}
})
}
</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-rtan" width="300" src="http://spartacodingclub.shop/static/images/rtans/SpartaIcon11.png"/>
<h1 id="text-rtan">나는 ㅇㅇㅇ하는 르탄이!</h1>
</div>
</div>
</body>
댓글