AJAX(Asynchronous JavaScript and XML)

  • 서버와 데이터를 교환하는 기술의 하나
  • 자바스크립트를 이용해서 비동기적으로 서버와 브라우저가 데이터를 주고 받는 방식을 의미한다.
  • 전체 페이지를 다시 로드 하지 않고도 웹 페이지의 일부를 업데이트 할 수 있다

JavaScript 비동기 통신 

댓글과 같은 페이지가 로드되지 않고 바로 업데이트 되는 형식

  • 객체선언
     > new XMLHttpRequest()객체 생성
  • form method
    • get일 때
      • xhttp객체.open('get','이름.jsp?전달할변수name=문자열')
      • xhttp객체.send() // url에 쿼리스트링으로 표현하기
    • post일 때
      • xhttp객체.open('post','이름.jsp');
      • xhttp객체.setRequestHeader( )
      • xhttp객체.send(data);
  • 응답
    xhttp객체.onreadystatechange = function(){ 응답했을 때 실행할 코드 (this.readyState | this.status) } 
    (onload / onloadend 등등)
    • readyState
      • 0 : open()메서드 수행전
      • 1 : 로딩중
      • 2 : 로딩완료
      • 3 : 서버처리중
      • 4 : 서버처리끝
    • status (서버의 처리결과)
      • 200 : 성공
      • 403 : 접근거부
      • 404 : 파일/페이지 없음
      • 304 : 요청오류
    • 응답에 성공했을 때, 그 페이지에 있는 text 가져오기
      this.responseText

get방식 예시

html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
const xhr = new XMLHttpRequest();
$(function(){
$('#asybut').on('click',function(){
// 입력한 이름과 전화번호 가져오기
let vname = $('#name').val();
if(vname.length < 1){
alert("이름을 입력하세요");
return;
}
let vtel = $('#tel').val();
if(vtel.length < 1){
alert("전화번호를 입력하세요");
return;
}
// 요청
xhr.open('get', 'test1.jsp?name='+vname+'&tel='+vtel);
xhr.send();
// 응답
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log("응답성공");
res = this.responseText;
$('#result1').html(res);
};
}
})
})
</script>
</head>
<body>
<div class="box">
<h3>비동기 전송과 동기 전송</h3>
비동기 전송 : 페이지 이동없이 결과를 출력 result1번에 출력<br>
동기 전송 : 페이지를 다시 로드하여 결과를 받는다
<form action="test1.jsp" method="get">
이름 <input name="name" id="name"><br>
전화번호 <input name="tel" id="tel"><br>
<br><br>
<input type="submit" value="동기" id="btn1">
<input type="button" value="비동기" id="asybut"> <br> <br>
</form>
<div id="result1"></div>
</div>
</body>
</html>

test1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#pname{
font-size : 2.0rem;
color : blue;
}
#ptel{
font-size : 1.5rem;
}
</style>
</head>
<body>
<h1>Hello~~</h1>
<p>클라이언트의 요청에 의해서<br>
서버내에서 실행되는 JSP파일입니다</p>
<%
//post 방식엔 반드시 인코딩 설정
request.setCharacterEncoding("UTF-8");
// 전송 시 데이터 - name , tel
String name = request.getParameter("name");
String tel = request.getParameter("tel");
// db 연결, CRUD -
// crud결과로 응답데이터 설정
%>
<p id="pname"><%=name %>님 환영합니다</p>
<p id="ptel"><%=tel %>로 전화할게요</p>
</body>
</html>

post방식 예제

html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../CSS/public.css">
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://localhost/Jqpro/js/jquery-3.7.1.js"></script>
<script>
const xhr = new XMLHttpRequest();
$(function(){
$('#asybut').on('click',function(){
// 입력한 이름과 전화번호 가져오기
let vname = $('#name').val();
if(vname.length < 1){
alert("이름을 입력하세요");
return;
}
console.log(vname);
let vtel = $('#tel').val();
if(vtel.length < 1){
alert("전화번호를 입력하세요");
return;
}
console.log(vtel);
// 요청
// 띄어쓰기 없이 작성할 것
data = `name=${vname}&tel=${vtel}`;
console.log(data);
xhr.open('post', 'test1.jsp', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
// 응답
xhr.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
console.log("응답성공");
res = this.responseText;
$('#result1').html(res);
};
}
})
})
</script>
</head>
<body>
<div class="box">
<h3>비동기 전송과 동기 전송</h3>
비동기 전송 : 페이지 이동없이 결과를 출력 result1번에 출력<br>
동기 전송 : 페이지를 다시 로드하여 결과를 받는다
<form action="test1.jsp" method="post">
이름 <input name="name" id="name"><br>
전화번호 <input name="tel" id="tel"><br>
<br><br>
<input type="submit" value="동기" id="btn1">
<input type="button" value="비동기" id="asybut"> <br> <br>
</form>
<div id="result1"></div>
</div>
</body>
</html>