오늘 배운 내용을 간단 요약하자면 다음 네 가지다.
- JavaScript 리뷰 + JQuery + AJAX 아키텍쳐 기본
- 프론트(JQuery, AJAX) + WAS + DB서버 비동기 연동 방법
- 실무에서 사용하는 JSON/XML 사례_기상청
- 실무에서 사용하는 JSON/XML 연습 with 스프링
동기식 방식과 비동기식 방식에 대해 먼저 알아야하는데,
클릭 한 번으로 요청하는 것 : 동기식 방식
클릭하지 않은 상태로 한 화면 안에서 여러 서버와 통신하는 방식 : 비동기식 방식(AJAX)
AJAX
JavaScript는 External, Internal, Inline 세 가지 방법이 있었다.
실습을 위해 Eclipse에서 Dynamic Web Project를 생성해준다.
이름은 web004로 했다.
아래의 링크로 들어가서 원하는 타입의 코드를 긁어올 수 있다.
https://www.w3schools.com/bootstrap5/bootstrap_buttons.php
Bootstrap 5 Buttons
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
여기까지 참고한 코드를 이용한 뒤 서버를 실행시키면
다음과 같이 뜬다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
</head>
<body>
아이디 입력 : <input class = "form-control"> <br>
<button class = "btn btn-warning" onclick="check()">글자수 체크</button>
</body>
</html>
여기서 alert함수를 추가해줄 수 있다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
function check() {
alert("alert가 실행됩니다.");
}
</script>
</head>
<body>
아이디 입력 : <input class = "form-control"> <br>
<button class = "btn btn-warning" onclick="check()">글자수 체크</button>
</body>
</html>
alertr가 귀찮으면 console.log로 변경해서 확인할 수 있도록 할 수 있다.
Body부분을 아래 코드로 수정해준다.
* 트리 구조는 부모, 자식, 형제 관계를 가지고 있다.
<body>
아이디 입력 :
<input id = "user" class = "form-control" value = "test"> <br>
<button class = "btn btn-warning" onclick="check()">글자수 체크</button>
</body>
글자수를 세어서 4글자 이상이면 안된다는 설정을 추가해준다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
function check() {
// alert("alert가 실행됩니다.");
console.log("alert가 실행됩니다.");
let userValue = document.getElementById("user").value
let len = userValue.length // String의 글자수
let resultTag = document.getElementById("result")
if (len >= 5) {
console.log("유효한 아이디입니다.")
resultTag.innerHTML = "유효한 아이디입니다."
} else {
console.log("유효하지 않은 아이디입니다.")
resultTag.innerHTML = "유효하지 않은 아이디입니다."
}
}
</script>
</head>
<body>
아이디 입력 :
<input id = "user" class = "form-control" value = "test">
<br>
<hr style = "color : red; height : 10px; width : 300px">
<div id = "result">Result</div>
<br>
<button class = "btn btn-warning" onclick = "check()">글자수 체크</button>
</body>
</html>
여기서 코드가 너무 길다 싶을 때 JQuery를 이용해 줄여줄 수 있다.
에서 다운받을 수 있다.
다운받은 것을 js 폴더로 넣어준다.
새로 monday이름의 파일을 복사해준 뒤
아래 코드를 추가해준다.
<script type = "text/javascript" src = "js/jquery-3.7.0.js"></script>
script와 body를 왔다갔다하지 않고,
body의 Button을 클릭했을 때 script로 넘어갈 수 있도록
코드를 변경해줄 수 있다.
각 기술과 용어를 정리하자면 다음과 같다.
- document.getElementById("user") → $('#btn1').click
- function() {} : 바디 부분을 먼저 읽고 오라는 의미
- $ = document
- $() : 돔트리를 먼저 읽어와라(body부분을 먼저 읽어와라)
- $(function(){함수내용}) : jquery에서는 실행할 내용을 함수로 만들어줄 때
입력값으로 이름 없는 함수(익명함수)를 많이 사용한다. - id면 # 써주면 됨
- fun까지 치고 Opt + Space 눌러서 자동완성
→ anonymus function 선택
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script type = "text/javascript" src = "js/jquery-3.7.0.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
/* $ = document
$() : 돔트리를 먼저 읽어와라(body부분을 먼저 읽어와라)
$(function(){함수내용}) : jquery에서는 실행할 내용을 함수로 만들어줄 때 입력값으로 이름 없는 함수(익명함수)를 많이 사용한다.
id는 # 입력 */
$(function() {
$('#btn1').click(function() {
// alert('JQuery 실행 완료')
let userValue = $('#user').val()
let resultTag = $('#result')
if(userValue.length >= 5) {
resultTag.html("유효한 아이디입니다.")
} else {
resultTag.html("유효하지 않은 아이디입니다.")
}
}) // btn1
$('#btn2').click(function() {
// 입력한 비밀번호가 1234와 동일하면 통과
alert("alert 실행")
let passValue = $('#pass').val()
let resultTag = $('#result')
if (passValue == '1234') {
resultTag.html("Pass")
} else {
resultTag.html("Fail")
}
// 입력한 값 지워주세요.
$('#pass').val("")
}) // btn2
// js는 오버로딩 가능 : val() :get(), val("") : set()의 의미
}) // $
</script>
</head>
<body>
아이디 입력 :
<input id = "user" class = "form-control" value = "test">
<br>
<button class = "btn btn-warning" id = "btn1">글자수 체크</button>
<hr style = "color : grey; height : 10px; width : 300px">
<div id = "result">Result</div>
<br>
<hr style = "color : red; height : 10px; width : 1500px">
<br>
<input id = "pass" class = "form-control" value = "1234"> <br>
<button class = "btn btn-warning" id = "btn2">비밀번호 체크</button>
</body>
</html>
https://developers.google.com/speed/libraries?hl=ko
호스팅된 라이브러리 | Hosted Libraries | Google for Developers
A stable, reliable, high-speed, globally available content distribution network for the most popular open-source JavaScript libraries.
developers.google.com
https://jqueryui.com/accordion/
Accordion | jQuery UI
Accordion Displays collapsible content panels for presenting information in a limited amount of space. Click headers to expand/collapse content that is broken into logical sections, much like tabs. Optionally, toggle sections open/closed on mouseover. The
jqueryui.com
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
$(function() {
}) // $
</script>
</head>
<body>
</body>
</html>
jquery의 기본 세팅이다.
여기서 요일 입력 값에 따라 평일과 주말에 대한
결과를 출력해주는 코드를 작성한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
// body 부분을 먼저 읽어온 후 입력값으로 넣은 함수 부분을 실행
$(function() {
$('#btn1').click(function() {
// alert("alert 호출됨")
let todayValue = $('#today').val()
let result = $('#result')
if (todayValue == '토' || todayValue == '일') {
result.text("주말")
// result.html("<img src = img/applewatch.jpg>")
} else {
result.text("평일")
// result.html("<img src = img/iphone.jpg>")
}
})
}) // $
</script>
</head>
<body>
<div class = "input-group mb-3 inpt-group-lg">
<span class = "input-group-text">오늘 요일 입력(요일 한 글자만 입력) : </span>
<input id = "today" class = "form-control" value = "금">
</div>
<hr style = "color : red; width : 300px;">
<div id = "result" class = "badge rounded-pill bg-danger">Result</div>
<hr style = "color : red; width : 300px;">
<button class = "mt-4 p-5 bg primary text-white rounded" id = "btn1">요일 체크</button>
</body>
</html>
JQuery 확인 문제
답안과 결과값은 아래.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
// body 부분을 먼저 읽어온 후 입력값으로 넣은 함수 부분을 실행
$(function() {
$('#b1').click(function() {
alert("alert 호출됨I")
let foodValue = $('#food').val()
let whereValue = $('#where').val()
let result = $('#result')
result.html("당신이 먹고싶은 음식은 " + foodValue + "이고, 당신이 가고싶은 장소는 " + whereValue + "입니다.")
}) // b1
$(function() {
$('#b2').click(function() {
alert("alert 호출됨II")
let siteValue = $('#site').val()
let result = $('#result')
if (siteValue == "movie") {
location.href = "http://cgv.co.kr"
} else {
location.href = "http://www.skyscanner.co.kr"
}
})
}) // b2
}) // $
</script>
</head>
<body>
<div class = "input-group mb-3 inpt-group-lg">
<span class = "input-group-text">먹고싶은 음식 : </span>
<input id = "food" class = "form-control" value = "복숭아">
</div>
<div class = "input-group mb-3 inpt-group-lg">
<span class = "input-group-text">가고싶은 장소 : </span>
<input id = "where" class = "form-control" value = "미국">
</div>
<hr style = "color : gray; width : 200px;">
<div id = "result" class = "badge rounded-pill bg-danger">Result</div>
<hr style = "color : gray; width : 200px;">
<button class = "mt-4 p-5 bg primary text-white rounded" id = "b1">기호 확인란</button>
<hr>
<div class = "input-group mb-3 input-group-lg">
<span class = "input-group-text">현재 내가 제일 많이 들어가는 사이트 : </span>
<input id = "site" class = "form-control" value = "movie">
<br>
<button class = "mt-4 p-5 bg-primary text-white rounded" id = "b2">가자</button>
</div>
</body>
</html>
+ 추가 문제 Ppt p. 238
추가문제
<!DOCTYPE html>
<!-- 댓글 달기 -->
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
// body 부분을 먼저 읽어온 후 입력값으로 넣은 함수 부분을 실행
$(function() {
let resultTag = $('#result')
$('#b1').click(function() {
alert("alert 호출됨I")
let replyValue = $('#reply').val()
resultTag.append("- " + replyValue + "<br>")
}) // b1
$('#b2').click(function() {
alert("alert 호출됨II")
resultTag.html("<img src = img/iphone.jpg width = 150 height = 150>")
}) // b2
$('#b3').click(function() {
alert("alert 호출됨III")
let replyValue = $('#reply').val()
let imgSrc = "<img src = img/iphone.jpg width = 100 height = 100>"
resultTag.append(imgSrc + replyValue + "<br>")
}) // b3
}) // $
</script>
</head>
<body>
<div class = "input-group mb-3 inpt-group-lg">
<span class = "input-group-text">입력 내용 : </span>
<input id = "reply" class = "form-control" value = "집 가고 싶다.">
</div>
<button class = "mt-4 p-3 bg primary text-white rounded" id = "b1">글자 추가</button>
<button class = "mt-4 p-3 bg primary text-white rounded" id = "b2">이미지 추가</button>
<button class = "mt-4 p-3 bg primary text-white rounded" id = "b3">댓글(글자 + 이미지)</button>
<hr style = "color : blue; width : 300px;">
<div id = "result" style = "width : 300px; height : 600px; background : lightyellow;"></div>
</body>
</html>
오늘 배운 한 가지 팁은 실무에서 그림을 그릴 일이 많은데
피그마를 다룰 줄 알면 피그마에서 하면 되고,
다루는 프로그램이 없다면 draw.io 주소창에 검색해서
아래와 같이 그리면 된다.
추가 문제_결제하기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.1.5.js"></script>
<script type="text/javascript">
$(function() {
$('button').click(function() {
var IMP = window.IMP; // 생략가능
IMP.init('iamport'); // 'iamport' 대신 부여받은 "가맹점 식별코드"를 사용
IMP.request_pay({
pg : 'inicis', // version 1.1.0부터 지원.
pay_method : 'card',
merchant_uid : 'merchant_' + new Date().getTime(),
name : '주문명:결제테스트',
amount : 1000,
buyer_email : 'iamport@siot.do',
buyer_name : '구매자이름',
buyer_tel : '010-1234-5678',
buyer_addr : '서울특별시 강남구 삼성동',
buyer_postcode : '123-456',
m_redirect_url : 'www.yourdomain.com/payments/complete'
}, function(rsp) {
if ( rsp.success ) {
var msg = '결제가 완료되었습니다.';
msg += '고유ID : ' + rsp.imp_uid;
msg += '상점 거래ID : ' + rsp.merchant_uid;
msg += '결제 금액 : ' + rsp.paid_amount;
msg += '카드 승인번호 : ' + rsp.apply_num;
} else {
var msg = '결제에 실패하였습니다.';
msg += '에러내용 : ' + rsp.error_msg;
}
alert(msg);
});
})
})
</script>
</head>
<body>
<button type="button">결제하기</button>
</body>
</html>
여기서 구매자의 추가 정보를 입력하도록 한다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.iamport.kr/js/iamport.payment-1.1.5.js"></script>
<script type="text/javascript">
$(function() {
$('button').click(function() {
alert("aaaa\ntest")
var IMP = window.IMP; // 생략가능
IMP.init('iamport'); // 'iamport' 대신 부여받은 "가맹점 식별코드"를 사용
IMP.request_pay({
pg : 'inicis', // version 1.1.0부터 지원.
pay_method : 'card',
merchant_uid : 'merchant_' + new Date().getTime(),
name : '주문명:결제테스트',
amount : $('#money').val(),
buyer_email : $('#email').val(),
buyer_name : $('user').val(),
buyer_tel : $('#tel').val(),
buyer_addr : '서울특별시 강남구 삼성동',
buyer_postcode : '123-456',
m_redirect_url : 'www.yourdomain.com/payments/complete'
}, function(rsp) {
if ( rsp.success ) {
var msg = '결제가 완료되었습니다.';
msg += '고유ID : ' + rsp.imp_uid;
msg += '상점 거래ID : ' + rsp.merchant_uid;
msg += '결제 금액 : ' + rsp.paid_amount;
msg += '카드 승인번호 : ' + rsp.apply_num;
} else {
var msg = '결제에 실패하였습니다.';
msg += '에러내용 : ' + rsp.error_msg;
}
alert(msg);
});
})
})
</script>
</head>
<body>
결제금액 : <input type = "text" id = "money"> <br>
이메일 : <input type = "text" id = "email"> <br>
구매자 성함 : <input type = "text" id = "user"> <br>
구매자 번호 : <input type = "text" id = "tel"> <br>
<button type="button">결제하기</button>
</body>
</html>
다음으로 DB에 연결을 해보려하는데,
그러려면 AJAX를 배워야한다.
AJAX
한 페이지에서 화면을 넘기지 않고 여러 서버와 통신하도록 해준다.
맛보기로 기상청 정보를 받아오는 예제를 해본다.
ok, weather, tour 이름의 세 html 파일을 만들어
각각 원하는 정보를 입력한다.
메인이 되는 ajax.html 파일에는 다음과 같이
ajax를 활용했다.
<!DOCTYPE html>
<!-- 기상청 AJAX -->
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
// body 부분을 먼저 읽어온 후 입력값으로 넣은 함수 부분을 실행
$(function() {
$('#b1').click(function() {
alert("b1 클릭됨")
$.ajax({
url : "ok.html",
success : function(x) {
alert('AJAX 성공. 받은 데이터는 "' + x + '"')
$('#d1').html(x)
}
})
}) // b1
$('#b2').click(function() {
alert("b2 클릭됨")
$.ajax({
url : "weather.html",
success : function(x) {
alert('AJAX 성공. 받은 데이터는 "' + x + '"')
$('#d2').html(x)
}
})
}) // b2
$('#b3').click(function() {
alert("b3 클릭됨")
$.ajax({
url : "tour.html",
success : function(x) {
alert('AJAX 성공. 받은 데이터는 "' + x + '"')
$('#d3').html(x)
}
})
}) // b3
}) // $
</script>
</head>
<body>
<button id="b1">AjaxTest 받아오기</button>
<button id="b2">기상청정보 받아오기</button>
<button id="b3">여행정보 받아오기</button>
<hr>
<div id="d1" style="width: 400px; height: 100px; background: lime;"></div>
<div id="d2" style="width: 400px; height: 100px; background: yellow;"></div>
<div id="d3" style="width: 400px; height: 100px; background: pink;"></div>
</body>
</html>
마지막 정리 기본 문제
마지막 정리 심화 문제
버튼을 누르면 링크로 이동하도록 설정했다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- Cmd + / : 자동 주석 -->
<!-- Latest compiled and minified CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js">
</script>
<script type = "text/javascript">
// body 부분을 먼저 읽어온 후 입력값으로 넣은 함수 부분을 실행
$(function() {
$('#btn1').click(function() {
let keywordValue = $('#keyword').val()
let result = $('#result')
location.href = "https://kin.naver.com/search/list.naver?query=" + keywordValue
})
$('#btn2').click(function() {
let keywordValue = $('#keyword2').val()
let result = $('#result')
location.href = "https://shopinghow.kakao.com/search/" + keywordValue
})
})
</script>
</head>
<body>
<div class = "input-group mb-3 input-group-lg">
<span class = "input-group-text">산, 바다, 강 중 어느 곳을 가고싶나요?</span>
<input id = "keyword" class = "form-control" value = "바다">
</div>
<hr style = "color : red; width : 300px;">
<button class = "mt-4 p-3 bg-primary text-white rounded" id = "btn1">가고싶은 곳 검색</button>
<hr>
<div class = "input-group mb-3 input-group-lg">
<span class = "input-group-text">구매하고싶은 물품은 무엇인가요?</span>
<input id = "keyword2" class = "form-control" value = "지바겐">
</div>
<hr style = "color : red; width : 300px;">
<button class = "mt-4 p-3 bg-primary text-white rounded" id = "btn2">사고싶은 물건 검색</button>
</body>
</html>