웹에서 비동기로 요청하면 페이지가 전체 새로고침 되지 않고 일부분만 업데이트된다.
사용자 입장에선 간편하게 사용할 수 있다는 장점이 있다.
ajax get 요청
ajax post 요청
동기 요청
동기 요청으로 하면 위 url 주소가 다른 것을 볼 수 있는데 페이지 이동이 일어난 것이다.
동기 요청 클릭!
getTest.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script type="text/javascript" charset="euc-kr">
function a(){
// "비동기 요청 객체" 생성
const xhttp = new XMLHttpRequest();
// 비동기 요청 응답이 왔을 때 자동 실행될 핸들러 등록
xhttp.onload = function(){
let res = document.getElementById("res");
res.innerHTML = decodeURI(xhttp.responseText);
// responseText : 서버로부터 받은 응답값
}
let param = "?name=" + f.name.value;
console.log(param);
console.log("f.name.value : "+f.name.value);
xhttp.open("GET", "${pageContext.request.contextPath}/ajaxtest/gettest?name="+encodeURI(encodeURIComponent(f.name.value)));
//xhttp.open("GET", "${pageContext.request.contextPath}/ajaxtest/gettest"+encodeURI(encodeURIComponent(param)));
// 전송을 보내기 위해 설정하는 함수
// 요청 전송방식, 서버페이지 url 설정. get방식인 경우 url 뒤에 파람 붙임
xhttp.send();
// 요청보냄
}
function b(){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
let res = document.getElementById("res");
res.innerHTML = decodeURI(xhttp.responseText);
}
let param = "name=" + f.name.value;
xhttp.open("POST", "${pageContext.request.contextPath}/ajaxtest/gettest");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// post 방식 enctype을 application으로 설정
xhttp.send(param);
}
// POST를 보내는 두 가지 방법
// ① application 일반 폼방식 ② multi part 파일 업로드 방식
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/ajaxtest/gettest" name="f">
<input type="text" name="name" ><br/>
<input type="button" value="ajax get 요청" onclick="a()">
<input type="button" value="ajax post 요청" onclick="b()">
<input type="submit" value="동기 요청">
</form>
<div id="res"></div>
</body>
</html>
GetTest.java
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("euc-kr");
response.setCharacterEncoding("euc-kr");
response.setContentType("text/html; charset=EUC-KR");
String name = request.getParameter("name");
System.out.println(name);
response.getWriter().append("get : hello "+name);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("euc-kr");
response.setCharacterEncoding("euc-kr");
response.setContentType("text/html; charset=EUC-KR");
String name = request.getParameter("name");
System.out.println(name);
response.getWriter().append("post : hello "+name);
}
}
const xhttp = new XMLHttpRequest();
❓ 서버는 클라이언트에게 결과를 어떻게 줘야할까
서버는 텍스트
, json
, xml
등의 형태로 결과를 줄 수 있다.
근데 왔는지 확인할 수 있는 것이 필요하다.
확인할 수 있게 밑에 있는 2번 자동 호출될 함수를 등록해야 한다.
xhttp.onload = function() {
// 받은 응답을 가지고 처리 코드 작성
// 익명 함수
}
xttp.open("param1", "param2");
param1
전송방식. post
, get
, patch
, update
, delete
(위 전송방식은 restfull api랑 spring 할 때 자세하게 배울 것이다.)
param2
요청받을 서버 페이지 경로
xhttp.open("GET", "ajax_info.txt");
보내기전에 설정하는 것 .
get방식으로 보낼 수도 있고 post로 보낼 수도 있다.
xhttp.send();
json에서는 가장 중요한 두 가지가 있다.
배열
과 객체
이다.
[ ] : 배열
{ } : 객체
jsontest.jsp : 객체
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script>
window.onload=function(){
let arr = ['aaa', 'bbb', 'ccc'];
let obj = {"name" : "aaa", "num" : 1, "tel" : "111", "flag" : true};
let html = "<h3>arr values</h3>";
for(i=0;i<arr.length;i++){
html += arr[i] + ", ";
}
html += "<br/><br/>";
html += "<h3>obj 속성들</h3>";
html += "name : " + obj.name + "<br/>";
html += "num : " + obj.num + "<br/>";
html += "tel : " + obj.tel + "<br/>";
html += "flag : " + obj.flag + "<br/>";
let div=document.getElementById("res");
div.innerHTML = html;
}
</script>
</head>
<body>
<div id="res"></div>
</body>
</html>
javatest2.jsp : 배열
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script>
let txt = '[{"num":1, "name" : "aaa", "tel": "111"}, {"num":2, "name" : "bbb", "tel": "222"}, {"num":3, "name" : "bbb", "tel": "333"}]'
let arr = JSON.parse(txt);
for(let obj of arr){
document.write("num : "+obj.num+"<br/>");
document.write("name : "+obj.name+"<br/>");
document.write("tel : "+obj.tel+"<br/><br/>");
}
</script>
</head>
<body>
<div id="res"></div>
</body>
</html>
AJAX : 비동기 자바스크립트와 xml
Asynchronous Javascript And XML
웹 동기 요청 : 요청을 보내면 응답페이지를 받아와서 전체 페이지가 바뀐다.
웹 비동기 요청 : 응답페이지가 출력된 상태에서 요청을 보낸다.
페이지 이동이 없고 해당 부분만 업데이트가 된다.
결과로 텍스트, json, xml 데이터를 받는다.
이클립스 프로젝트 WEB-INF>lib 안에
json-simple-1.1.1jar
파일 추가
JsonTest1.java
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
JSONObject obj1 = new JSONObject();
obj1.put("num", 1);
obj1.put("name", "aaa");
obj1.put("tel", "111");
JSONObject obj2 = new JSONObject();
obj2.put("num", 2);
obj2.put("name", "bbb");
obj2.put("tel", "222");
JSONObject obj3 = new JSONObject();
obj3.put("num", 3); // {"num" : 3}
obj3.put("name", "ccc"); // {"num" : 3, "name" : "ccc"}
obj3.put("tel", "333"); // {"num" : 3, "name" : "ccc", "tel" : "333"}
JSONArray arr = new JSONArray();
arr.add(obj1);
arr.add(obj2);
arr.add(obj3);
String txt = arr.toJSONString();
response.getWriter().append(txt);
// 데이터를 분석하는 것이 파싱이다.
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ajax2.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
const xhttp = new XMLHttpRequest();
xhttp.onload = function(){
let txt = xhttp.responseText;
// responseText : 응답값
alert(txt);
let html = '';
let arr = JSON.parse(txt);
// JSON.parse는 []을 만나면 배열로 해주고, {}을 보면 객체구나 하고 분석해서 변환해주는 작업이다.
// 여기서 에러가 난다면 json 표기를 잘못 넣은 것이다. 그래서 console이나 alert로 확인해보기
for(let obj of arr){
html += "num : " + obj.num + "<br/>";
html += "name : " + obj.name + "<br/>";
html += "tel : " + obj.tel + "<br/><br/>";
}
let res = document.getElementById("res");
res.innerHTML = html;
}
console.log(`${pageContext.request.contextPath}`);
xhttp.open("GET", "${pageContext.request.contextPath}/json/test1");
xhttp.send();
}
</script>
</head>
<body>
<div id="res"></div>
</body>
</html>