Ajax(비동기적 JavaScript 및 XML) 개요
Ajax는 2005년 제안된 기술로 JavaScript, XML, CSS, XHTML, DOM, XSLT 및 XMLHttpRequest를 결합한 웹 개발 접근법입니다. 서버 언어에 독립적이며(PHP/JAVA EE/.NET 호환), 텍스트/XML/JSON 형식의 데이터를 반환합니다.
Ajax의 핵심 가치
- 페이지 새로고침 없는 데이터 교환
- 부분적 UI 업데이트(예: 사용자명 중복 검증)
- 향상된 사용자 경험 제공
- 데이터베이스 연동 효율화
동작 원리
XMLHttpRequest 객체를 통해 서버와 비동기 통신 수행:
- XMLHttpRequest 인스턴스 생성
- 서버 요청 전송
- 서버 측 처리
- 응답 데이터 처리 및 UI 업데이트
XMLHttpRequest 핵심 속성
| 속성 | 설명 |
|---|---|
| readyState | 요청 상태 (0: 초기화 전, 4: 완료) |
| responseText | 텍스트 형식 응답 |
| responseXML | XML 형식 응답 |
| status | HTTP 상태 코드 |
브라우저 호환 객체 생성
function createXHR() {
let xhr;
try {
xhr = new XMLHttpRequest(); // 표준 브라우저
} catch (e) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP"); // IE 6+
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP"); // IE 5
} catch (e) {
alert("AJAX 미지원 브라우저");
return null;
}
}
}
return xhr;
}
사용자명 검증 예제
서블릿 구성 (web.xml):
<servlet>
<servlet-name>UserCheck</servlet-name>
<servlet-class>com.UserValidator</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserCheck</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>
서버 측 처리 (UserValidator.java):
protected void doPost(HttpServletRequest req, HttpServletResponse res) {
res.setContentType("text/plain");
res.setCharacterEncoding("UTF-8");
String username = req.getParameter("userid");
if (!"admin".equals(username)) {
res.getWriter().print("사용 가능한 아이디");
} else {
res.getWriter().print("이미 존재하는 아이디");
}
}
클라이언트 측 구현:
let xhrObj;
function verifyUser() {
xhrObj = createXHR();
if (xhrObj) {
const userInput = document.getElementById("userInput").value;
xhrObj.open("POST", "/validate", true);
xhrObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhrObj.onreadystatechange = handleResponse;
xhrObj.send("userid=" + userInput);
}
}
function handleResponse() {
if (xhrObj.readyState === 4 && xhrObj.status === 200) {
document.getElementById("result").innerText = xhrObj.responseText;
}
}
데이터 형식 비교
- HTML: 간단한 UI 업데이트에 적합
- XML: 복잡한 데이터 구조 전송 시 사용
- JSON: 경량 데이터 교환에 최적화 (권장)
JSON 응답 처리 예시
// 서버 측
response.getWriter().print("{'status':'available'}");
// 클라이언트 측
const response = JSON.parse(xhrObj.responseText);
console.log(response.status);
지역 선택 연동 예제
function loadRegions() {
xhrObj = createXHR();
if (xhrObj) {
const region = document.getElementById("mainRegion").value;
xhrObj.open("POST", "/getRegions", true);
xhrObj.onreadystatechange = updateRegionList;
xhrObj.send("region=" + region);
}
}
function updateRegionList() {
if (xhrObj.readyState === 4) {
const regions = JSON.parse(xhrObj.responseText);
const selectBox = document.getElementById("subRegion");
selectBox.innerHTML = "";
regions.forEach(region => {
const option = document.createElement("option");
option.text = region;
selectBox.add(option);
});
}
}