FRONTEND/Ajax

[Ajax] Ajax로 데이터 넘기기 (아이디,POST,clock )

꾸준히개발하자 2022. 3. 18. 14:07

 

 

 

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>Insert title here</title>

<script type="text/javascript">

	var XMLHttpRequest; // 비동기 방식으로 서버와 연결해줄수있는 객체 브라우저에 내장
						// 사용자 정의 변수명 
	function ajaxRequest() {
		
		// IE
		//XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); // 브라우저에따라 객체생성을 한다.
		// 크롬 
		XMLHttpRequest = new XMLHttpRequest();	
		XMLHttpRequest.open("GET","helloAjax_ok.jsp",true); // 보내서 처리 , true:비동기방식
		XMLHttpRequest.onreadystatechange = viewMessage; // 갔다가 온 콜백함수(데이터) , readyState 속성이 바뀌었을때 실행할 이벤트 핸들러를 지정한다.
		XMLHttpRequest.send(null); // get방식이기때문에 여기가 null , post일때 변수명=값 넣음
	}
	
	// 콜백함수 : 돌아오고 나면 실행됨
	function viewMessage() {
		
		// 서버에서 응답이 왔을때 실행되는 메소드
		var responseText = XMLHttpRequest.responseText; // 돌아오는 데이터가 text이면 , 돌아오는 데이터가 XML이면 responseXML 
		
		var divE = document.getElementById("printDIV"); // 출력할곳 id 
		
		divE.innerHTML = responseText;  // HTML형식으로 responseText를 출력
	}
</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();
	
	/* 너무왔다가 훅 가버리니까   */
	
	/* 서버가 작업을 하는동안  */
	for(int i=0; i<300; i++) {
		System.out.print("delay.....");

	}
%>

Hello Ajax!!!

 

 

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;
	
	XMLHttpRequest = new XMLHttpRequest(); // 객체생성
	
	function printClientTime(){
		var clientTimeSpan = document.getElementById("clientTimeSpan"); // span id="clientTimeSpan" 읽어와서 객체 만듬
		var now = new Date(); // 월분일시분초 보여줌
		
		
		var timeStr = now.getFullYear() + "년 "
			+ (now.getMonth() + 1) + "월 "
			+ now.getDate() + "일 "
			+ now.getHours() + "시 "
			+ now.getMinutes() + "분 "
			+ now.getSeconds() + "초";
		
		/* _ok 안함 그냥 자기시간 띄운거다  */
		 clientTimeSpan.innerHTML = timeStr;
		// 시간 바꾸기
		// 자기자신을 1초마다 다시실행
		setTimeout("printClientTime()",1000);
	}
		
	function requestTime() {
		// clock_ok.jsp로 감 
		
		XMLHttpRequest.open("GET","clock_ok.jsp",true);
		XMLHttpRequest.onreadystatechange = printServerTime; // 콜백함수
		XMLHttpRequest.send(null);
		
		setTimeout("requestTime()",1000); // 1초마다 불러오면 된다.
		
	}
	// 얘로 돌아옴
	function printServerTime() {
	
		if(XMLHttpRequest.readyState==4) {
			if(XMLHttpRequest.status==200) {
				
				
				var serverTimeSpan =
					document.getElementById("serverTimeSpan"); // id를 객체만듬 innerHtml 하기위해 
				
				serverTimeSpan.innerHTML = XMLHttpRequest.responseText;	
			}
		}
		
	}
	//body가 로딩될 때(창이 열릴때) printClientTime() 호출
	window.onload = function() {
		printClientTime();
		requestTime(); 
	}
</script>

</head>
<body>
<h1>Clock</h1>
<br/>
<hr/>

1. 현재 클라이언트 시간은<b><span id="clientTimeSpan"></span></b> 입니다<br/>
2. 현재 서버 시간은<b><span id="serverTimeSpan"></span></b> 입니다<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();
%>

<%= new Date() %> <!-- 시간만 돌려주면 된다.  -->

 

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>Insert title here</title>

<script type="text/javascript">


	var XMLHttpRequest; // 전역변수 선언
	
	XMLHttpRequest = new XMLHttpRequest(); 
		
	// onkeyup="requestGet(); 키업에 따라서 실행 "/>
	function requestGet() {
			
		var f = document.myForm;

		if(!f.userId) {
			alert("아이디 입력!");
			f.userId.focus();
			return;
		}
		var params = "?userId=" + f.userId.value;
		XMLHttpRequest.open("GET","ajaxId_ok.jsp" + params,true);
		XMLHttpRequest.onreadystatechange = viewMessage; // 돌아올때는 콜백함수
		XMLHttpRequest.send(null);	// get방식일때 null	
	}
	
	// 콜백함수
	function viewMessage() {
		if(XMLHttpRequest.readyState==4) {
			if(XMLHttpRequest.status==200) {
				
				var str = XMLHttpRequest.responseText;
				
				var divE = document.getElementById("resultDIV");
				divE.innerHTML = str; 
			}
		} else {
			// 데이터가 재대로 넘어오지 못하면
			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">

<!-- onkeyup="requestGet(); 손가락을 때는순간 requestGet() 호출  -->
아이디: <input type="text" name="userId" onkeyup="requestGet();"/>

</form>
<br/><br/><br/><br/>

<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 = "";
	
	// null 이아니면 실행
	if(!userId.equals("")) {
		
		for(int i=0; i<50000; i++) {
			System.out.print("delay");
		}
		
		if(userId.startsWith("suzi")){ // 아이디를 읽어왔으면 나중에 db에서 select 해오면 된다.
 			
			str = userId + "는 유효한 아이디 입니다.";
		} else {
			str = userId + "는 유효한 아이디가 아닙니다.";			
		}
	}
	
%>
<!-- 처리하고 str를 돌려줌 -->
<%=str%>

 

 

 

 

 

 

 

 

 

 

 

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>Insert title here</title>

<script type="text/javascript">

	// 객체를 전역변수로 만듬
	var XMLHttpRequest; 
	
function getXMLHttpRequest() {
		
	/* 크롬인지 브라우저인지 알아서 객체 생성  */	
	if(window.ActiveXObject) {
	
		try {
			//IE5.0이후버전
			XMLHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			//IE5.0이전버전
			XMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");				
			}
		} else { // NON-IE 크롬
			XMLHttpRequest = new XMLHttpRequest();
		}
	}
	
	function ajaxRequestGet() {
		/* myForm 에 있는 greting */
		var data = document.myForm.greeting.value;
		if(data==""){
			alert("데이터 입력!");
			document.myForm.greeting.focus();
			return;
		}
			//Get방식 : 한글이 깨짐 
			XMLHttpRequest.open("GET","ajaxGetPost_ok.jsp?greeting="+ data , true);
			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); // post방식으로 보냄 
			XMLHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			// post방식일때 application/x-www-form-urlencoded 를 써줘야함 
			
			XMLHttpRequest.onreadystatechange = viewMessage;
			XMLHttpRequest.send("greeting=" + data);

		}
		
	function viewMessage() {
		
		var divE = document.getElementById("printDiv"); // 폼 밖에 있어서 getElementById 객체 받아옴 
	
		/* readyState 0 : 객체생성 , readyState 1 : 정보설정 , readyState 2 : send메소드로 요청 , readyState 3 : 서버에서 응답오기 시작 , readyState 4 : 서버 응답 완료 */
		
		if(XMLHttpRequest.readyState==1||
				XMLHttpRequest.readyState==2||
				XMLHttpRequest.readyState==3){
			
			divE.innerHTML = 
				"<image src='./image/processing.gif' width='50' height='50'/>";
		} else if(XMLHttpRequest.readyState==4){
			// 4면 정상적으로 실행됨
			divE.innerHTML = XMLHttpRequest.responseText;
		}
		
		
	}
		// post방식에도 /* 크롬인지 브라우저인지 알아서 객체 생성  이 필요 
		// 그래서 getXMLHttpRequest() 위에서 브라우저에 따라 객체 생성	
		// 폼이 로딩이 될때 함수실행 - 함수는 getXMLHttpRequest(); 실행  - 브라우저에 의해서 XMLHttpRequest를 생성 , 
		
		
	//body가 로딩될 때(창이 열릴때) getXMLHttpRequest() 호출
	window.onload = function () {
		getXMLHttpRequest(); 
	}

		
</script>

</head>
<body>

<h1>AjaxGetPost</h1>
<hr/>

<form action="" name="myForm"> <!-- from 에서 method="post" enctype="application/x-www-form-urlencoded" post방식으로 보낼때 내장되어있어서 아쟉스에서 보낼때 위에 적어줘야함  -->
<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>

 

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); HTTP/1.1

	
	// 클라이언트의 ajax캐쉬를 삭제하는 명령어
	// 클라이언트가 처리한 결과를 자기가 가지고 있다. ajax만들어진 페이지를 가면 캐쉬가 쌓이게 되면서 충돌이 일어나므로 캐쉬내용을 지움 
	
	if(request.getProtocol().equals("HTTP/1.1")){
		response.setHeader("Cache-Control", "no-cache");
	}

%>

<%

	String greeting = request.getParameter("greeting"); // 데이터가 넘어옴
	
	// 처리하는 시간 필요
	for(int i=0;i<3500;i++){
	
	System.out.print("처리중....");
	
	}
%>

<!-- greeting 를 보낸다.  responseText; -->
<%="Server:" + greeting %>