본문 바로가기
study/Ajax

[Ajax] 22. Ajax

by 금이패런츠 2022. 4. 26.
728x90
반응형
//src/main/webapp/ajax/ajax.js
let ajax = null;
//XMLHttpRequest 객체 생성. ajax 객체
function getAjaxObject() {
	if(window.ActiveXObject) { //현재 브라우저가 익스플로러니?
		try {
			return new ActiveXObject("Msxml2.XMLHTTP") //버전에 따라 생성 방식
		} catch(e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP") 
			} catch(e2) {
				return null;
			}
		}
	} else if (window.XMLHttpRequest) { // 그 외 브라우저. 크롬, 사파리....
		return new XMLHttpRequest();
	} else {
		return null;
	}
}
//hello.jsp", "name=" + document.querySelector("#name").value, helloFromServer, "POST"
function sendRequest(url, params, callback, method) {
	ajax = getAjaxObject(); //XMLHttpRequest 객체 저장
	//method 매개변수값 존재?
	let httpMethod = method?method:"GET";
	if(httpMethod != "GET" && httpMethod != "POST") {
		httpMethod = "GET"; // GET/POST 값 둘중 한개 저장
	}
	//name = 홍길동
	let httpParams = (params == null || params == '')?null:params;
	let httpUrl = url; //hello.jsp
	if(httpMethod == "GET" && httpParams != null) {
		httpUrl = httpUrl + "?" + httpParams;
	}
	//ajax 객체초기화
	ajax.open(httpMethod, httpUrl, true); //POST, hello.jsp, true(비동기방식)
	//헤더정보 설정
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	//콜백함수 : 서버가 호출해주는 함수.
	ajax.onreadystatechange = callback; //helloFromServer 콜백함수 등록
	//서버요청
	ajax.send(httpMethod == "POST"?httpParams:null);
}

<!DOCTYPE html>
<!-- src/main/webapp/ajax/hello.html -->
<html>
<head>
<meta charset="UTF-8">
<title>ajax 연습</title>
<script type="text/javascript" src="ajax.js">
</script>
<script type="text/javascript">
	function helloToServer() {
		sendRequest("hello.jsp", "name=" + document.querySelector("#name").value, helloFromServer, "POST")
	}
	//ajax 객체에 등록된 콜백함수	: readyState의 상태가 변경될 때 호출됨.
	function helloFromServer() {
		/*
			ajax.readyState : ajax 객체의 상태 정보
				0 : ajax 객체 생성.
				1 : ajax.open() 된 경우. 준비 완료.
				2 : ajax.send() 된 경우. 서버로 요청. 서버에서 응답 전 인 상태.
				3 : 서버에서 응답이 일부만 전송된 상태.
				4 : 서버에서 응답이 완료된 상태.
				
			ajax.status : 서버의 응답코드
				200 : 정상응답.	
				404 : 요청페이지 없음. hello.jsp 페이지가 없는 경우.
				500 : 요청페이지에서 오류 발생. hello.jsp 페이지는 있지만 오류 발생.
		*/
		if(ajax.readyState == 4) { //서버에서 응답이 완료
			if(ajax.status == 200) { //정상적으로 처리
				console.log(ajax.responseText)
				hello.innerHTML = ajax.responseText;
			}
		}
	}
</script>
</head>
<body>
<input type="text" id="name" value="홍길동">
<input type="button" value="인사하기" onclick="helloToServer()">
<br>
<div id="hello"></div>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%--src/main/webapp/ajax/hello.jsp --%>
<% request.setCharacterEncoding("UTF-8"); %>
<h3>안녕하세요 <font color="blue">${param.name}</font>입니다.</h3>

jquery_ajax.pdf
0.30MB

 

 

728x90
반응형