
<h1>Ajax 개요</h1>
<p>
Ajax는 Asynchronous Javascript And XML이란 용어로<br> 서버로부터 데이터를 가져와 전체
페이지를 새로 고치지 않고 일부만 로드할 수 있게 하는 기법<br> 비동기식 요청을 함.
</p>
<h3>동기식/비동기식이란?</h3>
<p>
동기식은 서버와 클라이언트가 동시에 통신하여 프로세스를 수행 및 종료까지 같이하는 방식<br> 이에 반해 비동기식은
페이지 리로딩없이 서버요청 사이사이 추가적인 요청과 처리 가능
</p>
<h3>Ajax 구현(Javascript)</h3>
<h4>1. ajax로 서버에 전송값 보내기</h4>
<p>버튼 클릭시 전송값을 서버에서 출력</p>
<input type="text" id="msg-1">
<button onclick="jsFunc();">보내기(JS)</button>
function jsFunc() {
//1. XMLHttpRequest 객체생성
var xhttp = new XMLHttpRequest();
var msg = document.querySelector('#msg-1').value;
//2. 요청정보 설정
xhttp.open("GET", "/ajax/ex1.kh?msg=" + msg, true);
//3. 데이터 처리에 따른 동작함수 설정
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// status -> 200 (요청성공), 404(페이지 url 없음), 500(서버오류발생), 403(접근거부), 400(쿼리스트링 갯수오류)
console.log("서버 전송 성공")
} else if (this.readyState == 4 && this.status == 404) {
console.log("서버전송실패")
//콜백을 아직 하지 않아 404가뜬다
}
}
//4. 전송
xhttp.send();
}
@ResponseBody
@RequestMapping(value="/ajax/ex1.kh", method = RequestMethod.GET)
public void exerciseAjax(@RequestParam("msg")String msg) {
System.out.println("전송받은 데이터 : " + msg);
}
var xhttp = new XMLHttpRequest(); 로 객체를 생성하고xhttp.open("GET", "컨트롤러 연결주소?전송할변수명=" + 전송할값, true); 로 값을 controller로 전달할 주소와 전달값을 정해준다xhttp.onreadystatechange = function() { 성공/ 실패시의 함수 } 로 결과값을 출력한다xhttp.send(); 를 이용해 값을 전송한다.<h3>Ajax 구현(jQuery)</h3>
<h4>2. ajax(jQuery)로 서버에 전송값 보내기</h4>
<p>버튼 클릭시 전송값을 서버에서 출력</p>
<input type="text" id="msg-2">
<button onclick="jqueryFunc();">보내기(jQuery)</button>
function jqueryFunc() {
var message = $('#msg-2').val()
$.ajax({
url : "/ajax/ex1.kh",
data : {
"msg" : message
},
type : "get",
success : function() {
console.log("서버전성성공")
},
error : function() {
console.log("서버전송실패")
}
});
}
@ResponseBody
@RequestMapping(value = "/ajax/ex1.kh", method = RequestMethod.GET)
public void exerciseAjax(@RequestParam("msg") String msg) {
System.out.println("전송받은 데이터 : " + msg);
}
jquery는 이미 ajax설정이 되어있기에 더 간편하게 작동할수있다.
하지만 javascript처럼 세세하게 할수 없다는 단점이있다.
<h3>3. 버튼 클릭시 서버에서 보낸 값 수신</h3>
<button id="jq-btn3">서버에서 보낸값 확인</button>
<p id="confirm-area"></p>
<script>
$('#jq-btn3').on("click", function() {
$.ajax({
url : "/ajax/ex2.kh",
type : "get",
success : function(data) {
$('#confirm-area').html(data);
},
error : function() {
console.log('처리실패');
}
})
})
</script>
@ResponseBody
@RequestMapping(value = "/ajax/ex2.kh", produces = "text/plain;charset=utf-8", // utf-8로 인코딩해주는 코드
method = RequestMethod.GET)
public String eserciseAjax2() {
return "서버에서 왔습니다";
}
success : function(반환값){}<h4>4. 서버로 전송값 보내고 결과 문자열 받아서 처리</h4>
<p>숫자 2개를 전송하고 더한 값 받기</p>
첫번째 수 :
<input type="text" id="num-1">
<br> 두번째 수 :
<input type="text" id="num-2">
<br>
<button id="jq-btn4">전송 및 결과확인</button>
<p id="p4"></p>
$('#jq-btn4').on("click",function(){
var num1 = $('#num-1').val();
var num2 = $('#num-2').val();
$.ajax({
url:"/ajax/ex3.kh",
type:"get",
data : {"num1" : num1,
"num2" : num2
}, // 보내는 값 json방식으로 전송함 중괄호 사용
success : function(result){ // 받는 값
$('#p4').html(result);
},
error : function() {
console.log("처리 실패")
}
})
})
@ResponseBody
@RequestMapping(value = "/ajax/ex3.kh", produces = "text/plain;charset=utf-8", // utf-8로 인코딩해주는 코드
method = RequestMethod.GET)
public String eserciseAjax3(@RequestParam("num1") Integer first, @RequestParam("num2") Integer second) {
int result = first + second;
return String.valueOf(result);
}
data:{Json}을 활용하는것이다$.ajax({
url:"/ajax/ex3.kh",
type:"get",
data : {"num1" : num1,
"num2" : num2
}, // 보내는 값 json방식으로 전송함 중괄호 사용
success : function(result){ // 받는 값
$('#p4').html(result);
},
error : function() {
console.log("처리 실패")
}
})