AJAX란?

AJAX란 비동기 JavaScript와 XML을 말합니다. 간단히 말하면, 서버측 Scripts와 통신하기 위한 XMLHttpRequest객체를 사용하는 것을 말합니다. 서버측으로 다양한 형식(JSON, XML, HTML 및 일반 텍스트 형식 등)의 정보를 주고 받을 수 있습니다. AJAX의 강력한 특징은 페이지 전체를 리프레쉬 하지 않고서도 수행 되는 "비동기성"입니다. 이러한 비동기성을 통해 사용자의 Event가 있으면 전체 페이지가 아닌 일부분만을 업데이트 할 수 있게 해줍니다.

다시 말해 아래와 같이 두가지로 정리됩니다.

  • 페이지 일부분을 업데이트 하기 위한 정보를 서버에 요청할 수 있다.
  • 서버로부터 받은 데이터로 작업을 한다.


간단한 예제

<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">

  Make a request

</span>

<script type="text/javascript">

(function() {

  var httpRequest;

  document.getElementById("ajaxButton").onclick = function() { makeRequest('test.html'); };


  function makeRequest(url) {

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...

      httpRequest = new XMLHttpRequest();

    } else if (window.ActiveXObject) { // IE

      try {

        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");

      } 

      catch (e) {

        try {

          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        } 

        catch (e) {}

      }

    }


    if (!httpRequest) {

      alert('Giving up :( Cannot create an XMLHTTP instance');

      return false;

    }

    httpRequest.onreadystatechange = alertContents;

    httpRequest.open('GET', url);

    httpRequest.send();

  }


  function alertContents() {

    if (httpRequest.readyState === 4) {

      if (httpRequest.status === 200) {

        alert(httpRequest.responseText);

      } else {

        alert('There was a problem with the request.');

      }

    }

  }

})();

</script>


이 예제에서:

  • 사용자는 브라우저 상의 "Make a request" 라는 링크를 클릭합니다;
  • 그러면 같은 디렉토리 내의 HTML 파일의 이름인 test.html 를 파라미터로 하여 makeRequest() 함수를 호출합니다;
  • 브라우저는 서버로 요구를 보내고 onreadystatechange 에 설정된 alertContents() 함수가 수행됩니다;
  • alertContents() 함수는 서버로부터 응답을 받았는지와 정상적으로 처리된 응답인지를 검사하여 그 경우 test.html 파일의 내용을 파라미터로 alert() 함수를 호출합니다.


+ Recent posts