Sparta 웹개발 종합반 2주차 9~12강+숙제
09. Ajax 함께 연습하기
미세먼지 OpenAPI
http://openapi.seoul.go.kr:8088/6d4d776b466c656533356a4b4b5872/json/RealtimeCityAir/1/99
Ajax 기본골격
$.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){
console.log(response)
}
})
Ajax 연습
<script>
function q1() {
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>
미세먼지 수치가 70이상인 곳은 빨간색으로
<!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 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">
</ul>
</div>
</body>
</html>
미세먼지 수치가 70이상인 곳은 빨간색
10. Quiz_Ajax 연습하기(1)
서울시 OpenAPI(실시간 따릉이 현황)을 이용하기
console.log(response)
console.log(rows)를 개발도구에 자주 찍어보면서 확인한다.
내가 쓴 코드
<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 = ''
temp_html = `<li>${name} : ${rack} : ${bike}</li>`
$('#names-q1').append(temp_html);
}
}
});
}
</script>
정답 코드
<script>
function q1() {
$('#names-q1').empty();
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulbike",
data: {},
success: function (response) {
let rows = response["getStationListHist"]["row"];
for (let i = 0; i < rows.length; i++) {
let rack_name = rows[i]['stationName'];
let rack_cnt = rows[i]['rackTotCnt'];
let bike_cnt = rows[i]['parkingBikeTotCnt'];
let temp_html = `<tr>
<td>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`
$('#names-q1').append(temp_html);
}
}
})
}
</script>
let temp_html = ''
temp_html = `<li>${name} : ${rack} : ${bike}</li>`
->
let temp_html = `<tr>
<td>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`
기존 형식에 있는 데이터형식을 복사하여 데이터 대신 ${}로 바꿔준다.
+따릉이 대수가 5대 미만인 곳
내가 쓴 코드
<script>
function q1() {
$('#names-q1').empty();
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/seoulbike",
data: {},
success: function (response) {
let rows = response["getStationListHist"]["row"];
for (let i = 0; i < rows.length; i++) {
let rack_name = rows[i]['stationName'];
let rack_cnt = rows[i]['rackTotCnt'];
let bike_cnt = rows[i]['parkingBikeTotCnt'];
if(bike_cnt<5)
let temp_html = `<tr class="good">
<td>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`
else {
temp_html = `<tr>
<td>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</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;
}
.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 rack_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>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`
} else {
temp_html = `<tr>
<td>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</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>
*style안에 red를 넣는 것을 까먹었다.
*let temp_html = ''; 를 써서 비워준다.
11. Quiz_Ajax 연습하기(2)
jQuery 이미지태그 src 바꾸기 검색
$("#img_cat").attr("src", imgurl);
이러고 어떻게 해야될지 감이 안잡힘
<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>
생각보다 코드가 간단했음
먼저 , ajax 기본 골격을 끄는 것부터 생각했으면 접근할수 있지 않았을까 생각이 들었다.
imgurl : 바꿀 url를 넣어주는 것
12. 2주차 끝 & 숙제 설명
로딩이 되자마자 Ajax로 환율 API를 call 해가지고 rate를 찍어준다.
로딩 ?
<script>
$(document).ready(function () {
q1();
});
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>
페이지 로딩 끝나자마자 Ajax call를 해서 이미지를 바꿔준다.
원래 고양이를 보자를 누르면 Ajax call하고 그 결과를 가져와서 바꿔줌
이제는 로딩하자마자 자동으로 call한다.(새로고침)
HW. 2주차 숙제 해설
1주차에 완성한 쇼핑몰에, 환율 정보를 넣기
내가 쓴 코드
<p class="color">달러-원 환율:rate</p>
.color{
color:blue;
}
<script>
$(document).ready(function () {
q1()
});
function order() {
alert('주문이 완료되었습니다!');
}
function q1(){
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rate",
data: {},
success: function (response) {
let rate = ['rate'];
let temp_html = <p>{rate}</p>
}
});
}
</script>
결과
정답 코드
<!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 href="https://fonts.googleapis.com/css2?family=Jua&display=swap" rel="stylesheet">
<style>
* {
font-family: 'Jua', sans-serif;
}
.item-img {
width: 500px;
height: 300px;
background-image: url("https://t1.daumcdn.net/liveboard/nts/5bcccfbd33da4865817b9c606b6b852e.JPG");
background-position: center;
background-size: cover;
}
.price {
font-size: 20px;
}
.item-desc {
width: 500px;
margin-top: 20px;
margin-bottom: 20px;
}
.item-order {
width: 500px;
}
.btn-order {
margin: auto;
width: 100px;
display: block;
}
.wrap {
width: 500px;
margin: auto;
}
.rate {
color: blue;
}
</style>
<script>
$(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);
}
})
}
function order() {
alert('주문이 완료되었습니다!');
}
</script>
</head>
<body>
<div class="wrap">
<div class="item-img"></div>
<div class="item-desc">
<h1>양초를 팝니다 <span class="price">가격:3,000원/개</span></h1>
<p>이 양초는 사실 특별한 힘을 지니고 있어요!</p>
<p class="rate">달러-원 환율: <span id="now-rate">1219.15</span></p>
</div>
<div class="item-order">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">주문자이름</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">주소</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">전화번호</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>
function q1(){
$.ajax({
type: "GET",
url: "http://spartacodingclub.shop/sparta_api/rate",
data: {},
success: function (response) {
let rate = ['rate']; //response를 안붙임
let temp_html = <p>{rate}</p>
}
})
}
->
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); //now-rate가 감싸고있는 텍스트는 now_rate로 변경된다. .text():메소드는 선택한 요소의 내용을 새로운 단순 text로 변경한다.
}
})
}
<p class="color">달러-원 환율:rate</p> -> <p class="rate">달러-원 환율: <span id="now-rate">1219.15</span></p>
<span>은 텍스트의 특정부분을 묶는데 자주 사용,<div>처럼 특별한 기능을 갖고있지 않고 CSS와 함계 쓰인다.(block이 아닌 inline)
환율값을 1219.15를 값을 아예 지정했음을 알수 있었다.