자바스크립트 - XMLHttpRequest, readyState

반응형

XMLHttpRequest

XMLHttpRequest 객체는 HTTP 클라이언트 인터페이스를 구현합니다.
폼 데이터를 보내거나 서버로 부터 데이터를 받아오는 기능을 수행합니다.

 

 1. XMLHttpRequest 객체 생성

var httpRequest = null;

function requestMsg() {
    if(window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest(); //safari, firefox, chrome
    } else if(window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); //exploer
    } else {
        httpRequest = null;
 }

 

ActiveXObject : 인터넷 익스플로러에서는 ActiveXObject라는 독자적인 이름 사용했었습니다.
예전에는 XMLHttpRequest와 ActiveXObject를 둘다 사용하여서 브라우저를 검사하였지만, 요새는 XMLHttpRequest만 사용합니다.

 

2. Request 객체가 실제로 동작하는 과정

open(전송방식, 주소(URL), 비동기여부)

  • 전송방식 : GET, POST
  • 주소 : URL
  • 비동기여부
    • true -> 비동기
    • false -> 동기 : response가 올때 까지 httpReqeust.send()에서 브라우저는 대기 상태입니다.

 

send(데이터) 

  • 데이터: 객체 전송방식
    • GET방식일 경우 null
    • POST 방식일 경우에는 Argument, param값들
httpRequest.onreadystatechange = responsMsg;
httpRequest.open("GET", "hello.jsp", true);
httpRequest.send(null);

 

3. XMLHttpRequest.readyState 준비 상태

readyState는 이벤트가 일어날 때 마다, 변경됩니다.

responsMsg 변경될 때 마다 resopnsMsg 함수가 호출됩니다.

httpRequest.readyState

  • uninitalized, 초기화가 안된 상태
  • loading, 서버에 연결이 완료된 상태
  • loaded, 서버가 request를 받은 상태
  • interactive, 서버가 request를 처리하고 있는 상태
  • complete, request가 끝나고 response가 준비된 상태
 function responsMsg(){
    if(httpRequest.readyState == 4){
       if(httpRequest.status == 200){
          var msgView = document.getElementById("msgView");
          msgView.innerHTML = httpRequest.responseText;
          //hello.jsp 의 text를 받아와라
          console.log(httpRequest.responseText);
          //respons로 넘어온 text를 본 페이지 div 태그에 넣어라!
       }
    }
 }

 

결과 화면

모든 코드

exam01.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
    var httpRequest = null;
    function requestMsg(){
        if(window.XMLHttpRequest){
            httpRequest = new XMLHttpRequest(); //safari, firefox
        }else if(window.ActiveXObject){
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); //exploer
        } else {
            httpRequest = null;
        }
        
        //HttpRequest의 상태가 변화 되었을 때 호출되는 이벤트 함수
        httpRequest.onreadystatechange = responsMsg;
    
        //서버 안에 포함된 url만 가능
        httpRequest.open("GET", "hello.jsp", true);
        //httpRequest.open([전송 방식, [주소(URL)], [비동기여부])
        //true -> 비동기 : 
        //false -> 동기 : response가 올때까지 httpRequest.send()에서 브라우저는 대기 상태
        httpRequest.send(null);
    }
    
     function responsMsg(){
        if(httpRequest.readyState == 4){
            if(httpRequest.status == 200){
                var msgView = document.getElementById("msgView");
                msgView.innerHTML = httpRequest.responseText;
                //hello.jsp 의 text를 받아와라
                console.log(httpRequest.responseText);
                //respons로 넘어온 text를 본 페이지 div 태그에 넣어라!
            }
        }
    } 
</script>
</head>
<body>
    <h1>서버에서 받은 메시지</h1>
    <div id="msgView">
        <br>
        <input type="button" value="서버에 자료요청" onclick="requestMsg()">
    </div>
</body>
</html>

 

hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!--
    Ajax (Asychronous JavaScript and XML, 에이잭스)
    동기식 : 상대의 상태에 의해 다음 동작이 이루어지는 방식
    비동기식 : 상대의 상태에 상관 없이 일방적으로 동작하는 방식
    
    - HTML, CSS 같은 표현 정보
    - JavaScript, DOM 등의 동적인 화면 정보(상호작용)
    - 웹 서버와 비동기적인 데이터 교환
    (XMLHttpRequest, XML, XSLT, JSON, ...)
    
    XML (Entensible Markup Language)
        : 다목적 마크업 언어(태그 등을 이용하여 문서나 데이터의 구조를 표현)
        : HTML의 데이터 교환 한계를 극복하기 위해 만들어짐
  -->

<h1>Hello Ajax World</h1>
 

 

728x90
반응형