예제1
클라이언트(브라우저)에서 폼을 작성하고 제출 버튼을 클릭하면, JavaScript의 jQuery를 통해 Ajax POST 요청이 서버로 전송됩니다.
서버의 ajaxServer1.jsp는 요청을 받아서 폼 데이터(name, ph_number, address)를 가져옵니다.
JSP 파일은 가져온 데이터를 JSON 형식으로 출력합니다.
클라이언트는 JSON 응답을 받고, JavaScript의 success 콜백 함수에서 JSON 데이터를 사용하여 웹 페이지의 내용을 업데이트합니다.
| 이름 | |
|---|---|
| 번호 | |
| 주소 |
| [확인] 이름 | |
|---|---|
| [확인] 번호 | |
| [확인] 주소 |
JSP 페이지는 사용자로부터 이름, 번호, 주소를 입력받고, 제출 버튼을 클릭하면 jQuery를 사용해 Ajax 요청을 보내서 서버 측 ajaxServer1.jsp에서 처리된 결과를 받아옵니다.
ajaxClient1.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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <!-- 제이쿼리 -->
<script>
$(function(){
$("#buttonSubmit").on("click",function(){
$.ajax({
url:"./ajaxServer1.jsp",
type:"post",
data:$("#theForm").serialize(),
dataType: 'json',
success:function(res){
alert("성공");
$("#result_name").html(res.name);
$("#result_ph_number").html(res.ph_number);
$("#result_address").html(res.address);
},
error: function(err) {
alert("실패 원인 : " + err);
}
});
});
});
</script>
</head>
<body>
<form id="theForm">
<table border="1">
<tr>
<th>이름</th>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<th>번호</th>
<td><input type="text" id="ph_number" name="ph_number"></td>
</tr>
<tr>
<th>주소</th>
<td><input type="text" id="address" name="address"></td>
</tr>
</table>
<br>
<input id="buttonSubmit" type="button" value="제출">
</form>
<br>
<table border="1">
<tr>
<th>[확인] 이름</th>
<td style="width: 200px;"><span id="result_name"></span></td>
</tr>
<tr>
<th>[확인] 번호</th>
<td><span id="result_ph_number"></span></td>
</tr>
<tr>
<th>[확인] 주소</th>
<td><span id="result_address"></span></td>
</tr>
</table>
</body>
</html>
클라이언트로부터 받은 데이터를 JSON 형식으로 응답하는 서버 측 코드입니다.
ajaxServer1.jsp
<%@ page language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String name = request.getParameter("name");
String ph_number = request.getParameter("ph_number");
String address = request.getParameter("address");
%>
{
"name": "<%= name %>",
"ph_number": "<%= ph_number %>",
"address": "<%= address %>"
}
Ajax를 사용하여 서버와 비동기 통신을 하는 방식입니다.
HTML 폼 데이터를 서버로 전송하는 방식으로,
$("#theForm").serialize() 메서드를 사용하여 폼의 모든 데이터를 직렬화(serialization)하여 전송하고 있습니다.
클라이언트 측에서 서버로 데이터를 전송하고, 서버에서 처리된 응답 데이터를 클라이언트 측에서 받아와 웹 페이지의 일부를 업데이트하는데 사용됩니다.