<script>
// 전역변수 설정
let count = 1;
function hey() {
// count를 2로 나눈 나머지가 0이라면
if(count % 2 === 0)
alert('짝수입니다.')
else
alert('홀수입니다.')
count++
}
</script>
HTML의 요소들을 조작하는, 편리한 Javascript를 미리 작성해둔 라이브러리
Javascript로도 모든 기능(예 - 버튼 글씨 바꾸기 등)을 구현할 수는 있지만,
1) 코드가 복잡하고, 2) 브라우저 간 호환성 문제도 고려해야해서, jQuery라는 라이브러리가 등장
jQuery는 Javascript와 다른 특별한 소프트웨어가 아니라 미리 작성된 Javascript 코드입니다. 전문 개발자들이 짜둔 코드를 잘 가져와서 사용하는 것임을 기억해주세요! (그렇게 때문에, 쓰기 전에 "임포트"를 해야합니다!)
// js
document.getElementById('element').style.display = 'none';
// jQuery
$('#element').hide();
https://www.w3schools.com/jquery/jquery_get_started.asp
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
// input 박스 값 가져오기
$('#article-url').val();
// Input 박스 값 변경하기
$('#article-url').val('안녕');
// id 값이 post-box인 곳을 가리키고, hide()로 안보이게 한다.
$('#post-box').hide();
// show()로 보이게 한다. (= css의 display 값을 block으로 바꾼다.)
$('#post-box').show();
$('#post-box').hide();
$('#post-box').css('display');
$('#post-box').show();
$('#post-box').css('display');
// input 박스인 경우
$('#post-url').val('여기에 텍스트를 입력하면!');
// button등 인 경우
$('#btn-posting-box').text('포스팅 박스 닫기');
let temp_html = '<button>나는 추가될 버튼이다!</button>';
$('#cards-box').append(temp_html);
<button id="btn-posting-box" onclick="openclose()" class="btn btn-primary btn-lg">포스팅박스 열기</a>
<script>
function openclose() {
// id가 post-box인 태그의 display값 가져오기
let status = $('#post-box').css('display');
// display값이 block 이면
if (status == 'block') {
// post-box의 display 숨기기
$('#post-box').hide();
// btn-posting-box의 텍스트값 변경
$('#btn-posting-box').text('포스팅박스 열기');
} else { // display값이 none 이면
// post-box의 display 보이기
$('#post-box').show();
// btn-posting-box의 텍스트값 변경
$('#btn-posting-box').text('포스팅박스 닫기');
}
}
</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;
}
</style>
<script>
// 빈칸 체크 함수 만들기
function q1() {
// 1. input-q1의 입력값을 가져온다. $('# .... ').val() 이렇게!
// 2. 만약 입력값이 빈칸이면 if(입력값=='')
// 3. alert('입력하세요!') 띄우기
// 4. alert(입력값) 띄우기
let input_text = $('#input-q1').val();
if (input_text === '') {
alert('입력하세요!');
$('#input-q1').focus();
return;
}
}
// 이메일 판별 함수 만들기
function q2() {
// 1. input-q2 값을 가져온다.
// 2. 만약 가져온 값에 @가 있으면 (includes 이용하기 - 구글링!)
// 3. info.spartacoding@gmail.com -> gmail 만 추출해서 ( .split('@') 을 이용하자!)
// 4. alert(도메인 값);으로 띄우기
// 5. 만약 이메일이 아니면 '이메일이 아닙니다.' 라는 얼럿 띄우기
let input_text = $('#input-q2').val();
if (!input_text.includes('@')){
alert('이메일이 아닙니다.');
$('#input-q2').focus();
return;
}
let email = input_text.split('@')[1];
let domain = email.split('.')[0];
alert(domain);
}
// HTML 붙이기/지우기 연습
function q3() {
// 1. input-q3 값을 가져온다. let txt = ... q1, q2에서 했던 걸 참고!
// 2. 가져온 값을 이용해 names-q3에 붙일 태그를 만든다. (let temp_html = `<li>${txt}</li>`) 요렇게!
// 3. 만들어둔 temp_html을 names-q3에 붙인다.(jQuery의 $('...').append(temp_html)을 이용하면 굿!)
let text = $('#input-q3').val();
if (text === '') {
alert('이름을 입력하세요');
$('#input-q3').focus();
return;
}
let temp_html = `<li>${text}</li>`;
$('#names-q3').append(temp_html);
$('#input-q3').val('');
}
function q3_remove() {
// 1. names-q3의 내부 태그를 모두 비운다.(jQuery의 $('....').empty()를 이용하면 굿!)
$('#names-q3').empty();
}
</script>
</head>
<body>
<h1>jQuery + Javascript의 조합을 연습하자!</h1>
<div class="question-box">
<h2>1. 빈칸 체크 함수 만들기</h2>
<h5>1-1. 버튼을 눌렀을 때 입력한 글자로 얼럿 띄우기</h5>
<h5>[완성본]1-2. 버튼을 눌렀을 때 칸에 아무것도 없으면 "입력하세요!" 얼럿 띄우기</h5>
<input id="input-q1" type="text" /> <button onclick="q1()">클릭</button>
</div>
<hr />
<div class="question-box">
<h2>2. 이메일 판별 함수 만들기</h2>
<h5>2-1. 버튼을 눌렀을 때 입력받은 이메일로 얼럿 띄우기</h5>
<h5>2-2. 이메일이 아니면(@가 없으면) '이메일이 아닙니다'라는 얼럿 띄우기</h5>
<h5>[완성본]2-3. 이메일 도메인만 얼럿 띄우기</h5>
<input id="input-q2" type="text" /> <button onclick="q2()">클릭</button>
</div>
<hr />
<div class="question-box">
<h2>3. HTML 붙이기/지우기 연습</h2>
<h5>3-1. 이름을 입력하면 아래 나오게 하기</h5>
<h5>[완성본]3-2. 다지우기 버튼을 만들기</h5>
<input id="input-q3" type="text" placeholder="여기에 이름을 입력" />
<button onclick="q3()">이름 붙이기</button>
<button onclick="q3_remove()">다지우기</button>
<ul id="names-q3">
<li>세종대왕</li>
<li>임꺽정</li>
</ul>
</div>
</body>
</html>
서버와 클라이언트 간의 교류에서 일반적으로 많이 사용된다.
(이전에는 XML로 많이 쓰였으나 현재는 json으로 많이 사용)
{
"name":"moon",
"age":27
}
{
"name":"moon",
"hobby":["soccer","swimming"]
}
------------------------------------
{
"RealtimeCityAir": {
"list_total_count": 25,
"RESULT": {},
"row": []
}
}
let jsonText = '{"name":"moon", "age":27}';
let realObjext = JSON.parse(jsonText);
let jsonText2 = JSON.stringify(realdObject);
👉 API는 은행 창구와 같은 것!
같은 예금 창구에서도 개인 고객이냐 기업 고객이냐에 따라
가져와야 하는 것 / 처리해주는 것이 다른 것처럼,클라이언트가 요청 할 때에도, "타입"이라는 것이 존재합니다.
GET → 통상적으로! 데이터 조회(Read)를 요청할 때
예) 영화 목록 조회POST → 통상적으로! 데이터 생성(Create), 변경(Update), 삭제(Delete) 요청 할 때
예) 회원가입, 회원탈퇴, 비밀번호 수정
Ajax는 jQuery를 임포트한 페이지에서만 동작 가능
기본골격
$.ajax({
type: "GET",
url: "여기에URL을입력",
data: {},
success: function(response){
console.log(response)
}
})
$.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) // 서버에서 준 결과를 이용해서 나머지 코드를 작성
}
})
👉 리마인드
GET 요청은, url뒤에 아래와 같이 붙여서 데이터를 가져갑니다.
http://naver.com?param=value¶m2=value2
POST 요청은, data : {} 에 넣어서 데이터를 가져갑니다.
data: { param: 'value', param2: 'value2' },
$.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);
}
}
})
결과
중구 175
종로구 190
용산구 97
은평구 196
서대문구 190
마포구 100
광진구 154
성동구 127
<script>
function q1() {
// 여기에 코드를 입력하세요
$.ajax({
type: 'GET',
url: 'http://spartacodingclub.shop/sparta_api/seoulbike',
data: {},
success: function (response) {
$('#names-q1').empty();
let rows = response['getStationList']['row'];
for (let i = 0; i < rows.length; i++) {
let row = rows[i];
let rack_name = row['stationName'];
let rack_cnt = row['rackTotCnt'];
let bike_cnt = row['parkingBikeTotCnt'];
let tmp_html = '';
if (bike_cnt < 5) {
tmp_html = `<tr class="urgent">
<td>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`;
} else {
tmp_html = `<tr>
<td>${rack_name}</td>
<td>${rack_cnt}</td>
<td>${bike_cnt}</td>
</tr>`;
}
$('#names-q1').append(tmp_html);
}
}
})
}
</script>
결과
<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>
<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>
.attr('src', url);
사용