롸?
Ajax란? 본문
Ajax(Asynchronous Javascript And Xml)
1. 개요
웹 애플리케이션에서 풍부한 사용자 인터페이스(Rich Internet Application) 구현 기술로 비동기 통신방식이다
전통적인 웹에서는 웹서버에서 데이터를 처리한 후 응답 페이지를 html로 작성하지만 Ajax에서는 처리 결과 중에서 필요한 데이터만 XML, json, csv 등의 데이터로 전송하고 클라이언트에서 이를 받아서 결과 페이지를 작성한다. 이로써 데이터 처리속도와 인터페이스의 입출력 반응 속도를 증가고 서버에 요청한 처리 결과를 받기 전에 다른 작업을 병행 할 수 있게 한다.
2. XMLHttpRequest 객체 (XHR 객체)
3. 응답의 송수신 상태 : onreadystatechange 이벤트와 readyState, status 프로퍼티
-
웹서버로부터 송수신 상태가 변하면 이벤트가 발생
-
XHR객체.onreadystatechange = callback함수;
-
예, requestHttp.onreadystatechange = function() { ... readyState에 따라 코딩 ... }
-
readyState 속성값
-
0: 초기화이전(uninitialized) - 객체 생성만 되고 초기화 이전, 즉, open 수행전
-
1: 로딩중(loading) - 객체 생성 및 초기화, 그러나 send 수행전
-
2: 로딩완료(loaded) - send 수행 되었으나 헤더와 status 값 미도착
-
3: 서버 처리중(interactive) - 데이터 일부만 도착
-
4: 처리완료(completed) - 데이터 전부 도착
-
status 속성값
-
200: 성공 (OK)
-
403: 접근거부 (Forbidden)
-
404: 파일 없음 (Not Found)
-
500: 서버 내부 오류 (Internal Server Error)
4-1. 예제 GET 방식
function getFunc(){
var name = frm.name.value;
var age = frm.age.value;
fName = "getpost.jsp?name=" + name + "&age=" + age;
xhr = new XMLHttpRequest();
xhr.open("get", fName, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
processGet();
}else{
alert("err : " + xhr.status);
}
}
}
xhr.send(null);
}
function processGet(){
var data = xhr.responseText;
document.getElementById("show").innerText = "get : " + data;
}
4-2. 예제 POST 방식
function postFunc(){
var name = frm.name.value;
var age = frm.age.value;
xhr = new XMLHttpRequest();
xhr.open("post", "post.jsp", true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
processPost();
}else{
alert("err : " + xhr.status);
}
}
}
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("name=" + name + "&age=" + age);
}
function processPost(){
var data = xhr.responseText;
document.getElementById("show").innerText = "post : " + data;
}
참고
1. http://mm.sookmyung.ac.kr/~sblim/lec/xml-PBL/xml16-81ajax.htm
'WEB > 이론' 카테고리의 다른 글
apache vs nginx (0) | 2021.12.07 |
---|---|
웹 서버 vs WAS (0) | 2021.12.07 |
CGI (0) | 2020.02.25 |
bootstrap (0) | 2020.02.25 |
MIME type (0) | 2020.02.25 |