서버-클라이언트 통신 이해하기
- JSON은, Key:Value로 이루어져 있다. 자료형 Dictionary와 아주- 유사함
- RealtimeCityAir라는 키 값에 딕셔너리 형 value가 들어가있고, 그 안에 row라는 키 값에는 리스트형 value가 들어가있다.
클라이언트→서버: GET 요청 이해하기
API는 은행 창구와 같은 것!
GET → 통상적으로! 데이터 조회(Read)를 요청할 때 예) 영화 목록 조회
POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때 예) 회원가입, 회원탈퇴, 비밀번호 수정
GET 방식으로 데이터를 전달하는 방법
? : 여기서부터 전달할 데이터가 작성된다는 의미
& : 전달할 데이터가 더 있다는 뜻
예시) 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://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
data: {}, // 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두세요)
success: function(response){ // 서버에서 준 결과를 response라는 변수에 담음
console.log(response) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})
모든구의 미세먼지값 찍기
$.ajax({
type: "GET",
url: "http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99",
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);
}
}
});
*ajax 연습하기1
<!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 > 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>
</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 연습하기 2
<!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;
}
.urgent {
color : red;
}
</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 < 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>
</html>
*ajax 연습하기 3
<!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" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/>
</div>
</div>
</body>
</html>
*2주차 숙제
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<title>조명을 팝니다. | 부트스트랩 연습하기</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<style>
* {
font-family: 'Jua', sans-serif;
}
.myphoto {
background-image: url("https://image.ohou.se/i/bucketplace-v2-development/uploads/productions/156815629461267391.png?gif=1&w=640&h=640&c=c");
width: 500px;
height: 300px;
background-position: center;
background-size: cover;
border-radius: 10px;
}
.price {
font-size: 20px;
}
.page {
width: 500px;
margin: auto;
}
.item-desc {
width : 500px;
margin-top: 20px;
margin-bottom: 20px;
}
.item-order {
width : 500px;
}
.btn-order {
width :100px;
margin : auto;
display : block;
}
.rate {
color : blue;
}
</style>
<script>
function order() {
alert('주문이 완료되었습니다!')
}
$(document).ready(function(){
get_rate();
});
function get_rate() {
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rate",
data: {},
success: function (response) {
let now_rate = response['rate'];
$('#now-rate').text(now_rate);
}
})
}
</script>
</head>
<body>
<div class="page">
<div class="myphoto"></div>
<div class="item-desc">
<h1>조명을 팝니다 <span class="price" >가격 30,000원/개</span></h1>
<p>원하는 문구로 레터링하여 나만의 조명을 직접 만들어 보세요!</p>
<p class = "rate">달러-원 환율 : <span id="now-rate"></span></p>
</div>
<div class="item-order">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">주문자 이름</span>
</div>
<input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<label class="input-group-text" for="inputGroupSelect01">수량</label>
</div>
<select class="custom-select" id="inputGroupSelect01">
<option selected>--수량을 선택하세요--</option>
<option value="1">1개</option>
<option value="2">2개</option>
<option value="3">3개</option>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">주소</span>
</div>
<input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">전화번호</span>
</div>
<input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default">
</div>
<button type="button" onclick="order()" class="btn btn-primary btn-order">주문하기</button>
</div>
</div>
</body>
</html>
'웹개발 종합반' 카테고리의 다른 글
<스파르타 코딩 클럽>웹개발 종합반 2주차 -WIL (1) (0) | 2022.05.17 |
---|---|
<스파르타 코딩 클럽>웹개발 종합반 1주차 -WIL(2) (0) | 2022.05.15 |
<스파르타 코딩 클럽>웹개발 종합반 1주차 -WIL(1) (0) | 2022.05.14 |