<2주차> JQuery & Ajax
JQuery란?
미리 작성된 자바스크립트 코드를 말한다.
즉 , 편리한 자바스크립트를 미리 작성해둔 라이브러리를 뜻한다.
따라서 꼭 임포트를 먼저 해줘야한다!
javascript : document.getElementById("element").style.display = "none";
jquery : $('#element').hide();
---->훨씬 직관적이다.
https://www.w3schools.com/jquery/jquery_get_started.asp -> 구글 CDN
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
부트스트랩 템플릿을 import하면 자동으로 import되어 있다.
$('#article-URL').val(); //가져옴
$('#article-URL').val("장영실"); //넣음(입력)
$('#post-box').hide();
$('#post-box').show();
$('#post-box').css('display');
$('#btn-posting-box').text('랄라');
let temp_html = `<button>나는 버튼이다</button>`
$('#cards-box').append(temp_html)
1. 포스팅박스 열기 버튼을 누르면 openclose() 함수가 실행된다.
<body>
<p class="lead">
<a onclick="openclose()" id="btn-posting-box" class="btn btn-primary btn-lg" href="#" role="button">포스팅박스 열기</a>
</p>
<div class="posting-box" id="post-box">
<div class="form-group">
<label>아티클 URL</label>
<input type="email" class="form-control" id="article-URL" aria-describedby="emailHelp"
placeholder="">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">간단 코멘트</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">기사저장</button>
</div>
</body>
2. id=post-box 의 css의 상태를 가져와서 그에 대한 비교를 통해 jquery로 hide하거나 show 제어할 수 있다.
<script>
function openclose(){
let status = $('#post-box').css('display');
if( status == 'block'){
$('#post-box').hide();
$('#btn-posting-box').text('포스팅박스 열기');
} else {
$('#post-box').show();
$('#btn-posting-box').text('포스팅박스 닫기');
}
}
</script>
Ajax
ajax 기본 골격이다.
$.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){
console.log(response)
}
})
type: "GET" → GET 방식으로 요청한다.
url: 요청할 url
data: 요청하면서 함께 줄 데이터 (GET 요청시엔 비워두기)
success: 성공하면, response 값에 서버의 결과 값을 담아서 함수를 실행한다.
**************
GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다. http://naver.com?param=value?param2=value2
POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다. data: { param: 'value', param2 'value2' }
**************
예시
<서울시 따릉이 현황 openAPI >
<!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 station_name = rows[i]['stationName']
let rack_cnt = rows[i]['rackTotCnt']
let parking_cnt = rows[i]['parkingBikeTotCnt']
let temp_html = ``
if(parking_cnt < 5) {
temp_html = `<tr class="urgent">
<td>${station_name}</td>
<td>${rack_cnt}</td>
<td>${parking_cnt}</td>
</tr>`
}else {
temp_html = `<tr>
<td>${station_name}</td>
<td>${rack_cnt}</td>
<td>${parking_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>