본문 바로가기

Ajax & jQuery

Ajax(2) - get/post 방식 비교, ID 유효성 검사, javascript를 이용한 Ajax 구현

- Ajax는 필수기술 중 하나, 매우 중요! 네이버에서 자동으로 바뀌는 부분들은 다 Ajax로 구현됨 
- jQuery도 부트스트랩처럼 CDN이 있음. jQUERY 사이트 > view source
- 나중엔 Javascript만을 이용해 server, view도 컨트롤 할 수 있음

1. Ajax 의 get방식과 post 방식 비교
2. Ajax를 활용한 ID 유효성 검사
3. Javascript를 이용한 Ajax 구현

1. Ajax - Get방식과 Post 방식 비교

 

ajaxGetPost.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AjaxGetPost</title>

<script type="text/javascript">

	var XMLHttpRequest;
	
	function getXmlHttpRequest() {
		
		if (window.ActiveXObject) { //IE인 경우

			try {

				//IE 5.0 이후 버전
				XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");

			} catch (e) {
				XMLHttpRequest = ActiveXObject("Microsoft.XMLHTTP");
			}

		} else { // Non-IE

			XMLHttpRequest = new XMLHttpRequest();

		}
		
	} // XML 객체 생성 완료 한 후에 위의 전역변수에다가 넣어줌
	
	

	function ajaxRequestGet() {


		var data = document.myForm.greeting.value;

		if (data == "") {

			alert("데이터를 입력하세요!");
			document.myForm.greeting.focus();
			return;

		}

		XMLHttpRequest.open("GET", "ajaxGetPost_ok.jsp?greeting=" + data, true);
		//GET방식이니깐 이렇게 ? 붙여서 데이터 건네주는거임

		XMLHttpRequest.onreadystatechange = viewMessage;
		XMLHttpRequest.send(null);

	}
	
	function ajaxRequestPost() {

		var data = document.myForm.greeting.value;

		if (data == "") {

			alert("데이터를 입력하세요");
			document.myForm.greeting.focus();
			return;

		}

		XMLHttpRequest.open("POST", "ajaxGetPost_ok.jsp", true);
		//GET방식이니깐 이렇게 ? 붙여서 썼던것임
		
		XMLHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		// form으로 감싸는게 POST방식이니깐 => enctype도 명시해주기 (ex.파일업로드)	
				
		XMLHttpRequest.onreadystatechange = viewMessage;
		XMLHttpRequest.send("greeting=" + data); // POST 방식의 데이터 넘기는 방법
		
		//POST 방식일 때는 한글 '수지'써도 잘 넘어감 
		//GET은 한글은 에러뜸
		
	}

	function viewMessage() {

		var divE = document.getElementById("printDIV");

		//4,200일때만 처리작업을 했는데 실무에서 쓸 때는 이렇게 씀
		
	if (XMLHttpRequest.readyState == 1 || //요청페이지 정보 설정
		XMLHttpRequest.readyState == 2 || //요청보내기 시작
		XMLHttpRequest.readyState == 3) { //서버에서 응답오기 시작 (작업이 다 끝난건 아니고)

			// 1,2,3 => 데이터가 온 상태 X , 4 => 데이터가 완벽하게 온 상태

			divE.innerHTML = "<img src='../image/processing.gif' width='50' height='50'/>";

			// 이미지 띄움

		} else if (XMLHttpRequest.readyState == 4) { // 서버 응답 완료 

			divE.innerHTML = XMLHttpRequest.responseText;
			// response로 넘어오는 Text를 html형식으로 printDIV 객체에 넣어줌
		}
	}

	//  Windows 폼이 시작되자마자, 자동으로 getXmlHttpRequest() 메소드가 실행되게끔 
	// (get,post방식 둘다 필요해하는 메소드니깐 위로 빼놓은 것)
	window.onload = function() {
		getXmlHttpRequest();
	}
	// 이런 onload는 보통 맨 아래에 써줌
</script>


</head>
<body>

<h1>ajaxGetPost</h1>

	<form action="" name="myForm">
		<input type="text" name="greeting" /> 
		<input type="button" value="Get전송" onclick="ajaxRequestGet();" /> 
		<input type="button" value="Post전송" onclick="ajaxRequestPost();" />
	</form>

	<div id="printDIV" style="border: 1px solid blue; width: 50%"></div>


</body>
</html>

 

대기시간에 사용할 gif 파일을 image 경로에 저장

 

 

ajaxGetPost_ok.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
	
	String protocol = request.getProtocol();
	System.out.print(protocol); // HTTP1.0 or HTTP1.1 둘중 하나 나옴 (대부분이 1.1)
	
	// Ajax는 한번 실행하면 클라이언트에 캐시가 남음. => 데이터를 바꿔도 잘 바뀌지 않음
	
	// 클라이언트 캐쉬 제거 작업
	response.setHeader("Pragma","no-cache");
	response.setHeader("Cache-Control","no-store"); // HTTP1.0 일 때, 캐시를 지우는 방법
	response.setHeader("Cache-Control","no-cache"); // HTTP1.1 일 때, 캐시를 지우는 방법
	
	// 세션 삭제 후 (로그아웃) 뒤로가기 접근 방지
	response.setDateHeader("Expire",0);
	
/* 	
	// 이렇게 줘도 됨 (위랑 똑같은 말)

	if(request.getProtocol().equals("HTTP/1.1")) {
		
		response.setHeader("Cache-Control","no-cache");
		
	} */
	
	String greeting = request.getParameter("greeting");
	
	for (int i=0; i<35000; i++) {
		System.out.print("기다려..처리중...\r\n");
	}
	
%>


<%="Server:" + greeting %>

2. Ajax를 활용한 ID 유효성 검사

 

ajaxId.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax ID 확인</title>

<script type="text/javascript">

	var XMLHttpRequest;
	
	function requestGet() {
		
		XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); //IE 5.0이후 버전용
		
		if(!document.myForm.userId.value) {
			
			alert("아이디를 입력하세요!");
			document.myForm.userId.focus();
			return;
			
		}
		
		var params = "?userId=" + document.myForm.userId.value;
		
		XMLHttpRequest.open("GET", "ajaxId_ok.jsp" + params, true);
		XMLHttpRequest.onreadystatechange = viewMessage;
		XMLHttpRequest.send(null);
		
		
	}
	
	function viewMessage() {
		
		if (XMLHttpRequest.readyState == 4) {
			if (XMLHttpRequest.status == 200) {
				
				var str = XMLHttpRequest.responseText;
				
				var divE = document.getElementById("resultDIV");
				divE.innerHTML = str; // text를 html 형식으로 resultDIV 객체에 넣어준다
				
			}

		} else {	// 데이터가 돌아오지 않는상태 (1,2,3)에서는 그림띄워라
			
			var divE = document.getElementById("resultDIV");
			divE.innerHTML =
				"<img src='../image/loading.gif' width='15' height='15'/>";
			
		}
		
	}


</script>
</head>
<body>

<h1>Ajax ID 확인</h1>
<hr/>

<form action="" name="myForm">

아이디:<input type="text" name="userId" onkeyup="requestGet();">
<!-- onkeyup: 키보드 떼는 순간 바로 실행-->

</form>

<div id="resultDIV" style="color: red; border: 1px solid; #000000; width:40%"></div>


</body>
</html>

 

ajaxId_ok.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
	
	String userId = request.getParameter("userId");
	
	String str="";
	
	if(!userId.equals("")){
		
		for(int i=0; i<50000; i++) {
			
			System.out.println("delay..");
			
		}
		// DB에 쿼리를 이용해서 읽어왔다고 가정하에 진행 
		if (userId.startsWith("suzi"))
			str = userId + "는 유효한 아이디 입니다";
		else
			str = userId + "는 유효한 아이디가 아닙니다";
		
	}
	
	
%>

<%=str %>

<!-- 서버단에서 돌아가는 값은 str -->

 

 

 

3. Ajax를 활용한 Server & Client 시간 체크하기

활용 - 지문 찍어서 출근체크하는 회사의 경우, 해당 local 컴퓨터의 시간이 아니라 다른 중요 server 컴퓨터의 시간을 읽어와서 시간체크를 함. -> 출근체크 시간을 조작할 수 없음

 

 

clock.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

<script type="text/javascript">

	var XMLHttpRequest;
	
	//서버에 보내는 코딩이 없음
	
	function printClientTime() {
		
		var clientTimeSpan =
			document.getElementById("clientTimeSpan");
		
		var now = new Date(); //자기자신의 Date에서 시간출력해줌
		var timeStr = now.getFullYear() + "년 "
					+ (now.getMonth() + 1) + "월 "
					+ now.getDate() + "일 "
					+ now.getHours() + "시 "
					+ now.getMinutes() + "분 "
					+ now.getSeconds() + "초 "
					
					
		clientTimeSpan.innerHTML = timeStr;	
		
		//정해진 시간마다 재실행
		// 1초마다 자기 자신을 호출 => 1초마다 시간이 바뀜
		setTimeout("printClientTime()",1000); 
		
	}
	
	//서버시간측정
	function requestTime() {
		
		XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
		
		//아무것도 넘기는 거 없을 때 dummy라고 넘겨줌 (안써줘도되고)
		XMLHttpRequest.open("GET", 
				"clock_ok.jsp?dummy=" + new Date().getDate(), true);
		
		// <기본 4가지 요소> 
		// method : GET
		// url : clock_ok.jsp
		// data : dummy = new Data().getDate()
		// callback함수 : printServerTime
		
		// javascript에
		// 4개의 값만 넘겨주면 이 작업을 해주는 함수를 만들것임
		// (마치 createXMLHttpRequest() 하나 만들어놓고 XMLHttpRequest 객체 생성했던것처럼)
		
		
		// new Data().getDate() 이것도 서버에서 쓰는거 아님. 아무값이나 넘겨준거
		XMLHttpRequest.onreadystatechange = printServerTime;
		XMLHttpRequest.send(null);
		
		setTimeout("requestTime()",1000); //자기 자신을 1초마다 다시 실행해야, 서버의 시간도 1초마다 읽어오니깐
		
	}
	
	function printServerTime() {
		
		if (XMLHttpRequest.readyState == 4) {
			
			if (XMLHttpRequest.status == 200) {
				
				// 출력할 부분의 객체 가지고 오고
				var serverTimeSpan =
					document.getElementById("serverTimeSpan");
				
				serverTimeSpan.innerHTML = 
					XMLHttpRequest.responseText;
				
			} else {
				//status가 200이 아닌 경우
			}
		} else {
			// readyState가 4가 아닌 경우
		}
		
	}
	
	// 시작점은 반드시 외부에서 따로 호출해줘야함 (client도 server시간도 )
	window.onload = function() {
		
		printClientTime(); // client 시간
		requestTime(); // server 시간
		
	}


</script>

</head>
<body>

<h1>Clock</h1>

1.현재 클라이언트 시간은 <span id="clientTimeSpan"></span>입니다.<br/>
2. 현재 서버 시간은 <span id="serverTimeSpan"></span>입니다.<br/>

</body>
</html>

 

 

clock_ok.jsp

<%@page import="java.util.Date"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
	
	String protocol = request.getProtocol();
	// HTTP1.0 / HTTP1.1 둘중 하나 나옴 (대부분이 1.1)
	
	// 클라이언트 캐시 지우기 
	response.setHeader("Pragma","no-cache");
	response.setHeader("Cache-Control","no-store"); 
	response.setHeader("Cache-Control","no-cache");
	
	// 세션 삭제 후 (로그아웃) 뒤로가기 접근 방지
	response.setDateHeader("Expire",0);
	
%>

<%=new Date()%> 

<!-- java.util 의 date() 함수 반환 -->
<!-- 지금 예제에서 ajax 서버는 결국 내 컴퓨터에서 실행되니깐
로컬 컴퓨터, 서버 컴퓨터 같음 그래서 시간이 똑같이 나올 수 밖에 없음 -->

서버PC와 로컬PC가 같아서 시간이 똑같이 나옴

 

 

4. javascript를 이용한 ajax 구현

 

helloAjax.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>helloAjax</title>

<script type="text/javascript">

	var XMLHttpRequest;
	
	function ajaxRequest() {
		
		//IE : 익스플로러에서만 실행
		XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		
		//non IE (IE 11버전도 이렇게 씀)
		//XMLHttpRequest = new XMLHttpRequest();
		
		XMLHttpRequest.open("GET", "helloAjax_ok.jsp", true); // 비동기방식 : true
		XMLHttpRequest.onreadystatechange = viewMessage; // callback 함수. (갔다가 돌아왔을 때 자동실행할 함수)
		XMLHttpRequest.send(null); //GET방식일땐 null
		
		
	}
	
	// 서버로부터 응답이 왔을 때 실행되는 메소드
	function viewMessage() {
		
		var responseText = XMLHttpRequest.responseText; //Text형태로 받을것임
		
		var DivE = document.getElementById("printDIV");
		DivE.innerHTML = responseText; // Text를 html형식으로 printDIV 객체에 넣어준다
		
	}
</script>
</head>
<body>

<h1>Hello Ajax</h1>
<input type="button" value="클릭" onclick="ajaxRequest();">

<br/><br/>

<!-- 처리결과 여기다가 뿌려줄거임 -->
<div id="printDIV" style="border: 1px solid red; width: 50%"></div>

</body>
</html>

 

helloAjax_ok.jsp

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	request.setCharacterEncoding("UTF-8"); 
	String cp = request.getContextPath(); 
	
	//이미지 잘 보기 위해 delay 시간 걸음
	//서버가 연산하는 시간을 임의로 만듬 (실제코딩에선 안씀)
	for (int i=0; i<300; i++) {
		System.out.print("delay .... ");
	}

%>


어려운 Ajax!