본문 바로가기

Ajax

Ajax - (3) XML 파일 읽어서 웹 브라우저에 출력하는 Ajax 예제

HTML 소스

<!DOCTYPE html>
<html lang="ko" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Ajax 실습 03-5 : 2019.09.29</title>
    <style>
    body {background:#000; color:#fff;}
    </style>

  </head>
  <body>
    XML 파일 실습입니다.<br>
    <button type="button" onclick="mySend()" >파일수신</button>
    <div id="result"></div>
    <script type="text/javascript">
      var xhttp;

      function createHttpRequest(){
        xhttp = new XMLHttpRequest();
      }

      function  mySend(){
        createHttpRequest();
        xhttp.onreadystatechange = callFunction;
        xhttp.open("GET","sample.xml", true);
        xhttp.send(null);

      }
      function callFunction(){
        if(xhttp.readyState == 4){
          if(xhttp.status == 200){
            var responseData = xhttp.responseXML;
            var titles = responseData.getElementsByTagName("title");
            var title = titles[0].firstChild.nodeValue;
            var artists = responseData.getElementsByTagName("artist");
            var artist = artists[0].firstChild.nodeValue;
            document.getElementById("result").innerHTML = title +"\t"+ artist;

          }
        }
      }
    </script>
  </body>
</html>

XML 소스

<?xml version="1.0" encoding="UTF-8" ?>
<song>
  <title>파랑새</title>
  <artist>이문세</artist>
  <album>1집</album>
  <year>1995</year> 
</song>

설명

Ajax xml JavaScript 실습 화면

22~27번라인 : createcreateHttpRequest(); 함수를 호출하여 XMlXMLHttpRequest 객체를 새엉하고 GET 방식으로 서버에 sample.xml 파일을 비동기로 요청합니다. 서버의 응답 처리를 위해서 onreadystatechange 프로퍼티에서는 readyState 반환값에 따라서 자동으로 호출하는 callFunction 함수를 설정합니다.

 

31번 라인 : XML 형식으로 응답 데이터 처리를 위해서 responseXML 프로퍼티를 사용합니다.

 

32~33번 라인 : DOM API 중에서 태그명으로 참조하기 위한 getgetElementsByTagName("title") 메서드를 사용하여 지정된 <title> 태그에 해당하는 반환값을 배열로 받습니다. 반환된 배열의 첫 번째 값을 title 변수에 저장한다.

 

34~35번 라인 : 32번 라인과 마찬가지로 DOM API 메서드와 태그명을 사용하여 <artist> 태그에 저장된 내용을 배열로 반환받습니다. 반환된 배열의 첫 번째 값을 artist 변수에 저장합니다.

 

 

 

 

728x90
300x250