XML 데이터를 ajax 로 받아오는 예제입니다. GET 으로 test.xml 에 요청하고, 그 결과 값을 보기좋게 HTML로 출력합니다.

test.xml 에는 아래 xml 로 구성되어 있을 때의 결과입니다.

<?xml version="1.0" encoding="utf-8"?>
<node>
  <book>도서1</book>
  <book>도서2</book>
  <list>
    <item>1권</item>
    <item>2권</item>
  </list>
</node>

<script>
function getXMLHttps() {
  if (typeof XMLHttpRequest != 'undefined') {
    return new XMLHttpRequest();
  } else {
    try {
      return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try{
       return new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e){
        alert("Ajax를 지원하는 브라우저가 아닙니다.");
        return;
      }
    }
  }
}

function dynamic(){
  var req = getXMLHttps();
  req.onreadystatechange = function(){
    if (this.readyState === 4 && this.status === 200) {
      parseXML(this.responseXML);
    }
  }
  // 사용자 정의 함수
  parseXML = function(data) {
    var txt = "";
    var a = data.getElementsByTagName("node")[0];
    for(var i = 0; i < a.children.length; i++){
      if(a.children[i].tagName == "book"){
        txt += "book" + (i+1) + ": ";
        txt += a.children[i].textContent + "<br/>";
      }else if(a.children[i].tagName == "list"){
        txt += "list: ";
        txt += a.children[i].children[0].textContent + ", ";
        txt += a.children[i].children[1].textContent;
      }
    }
    document.getElementById("test").innerHTML = txt;
  }

  req.open("GET", "test.xml", true);
  req.send();
}
</script>

<div id="test"></div> 
<button onclick="dynamic()">전송</button>

<!--
결과:
book1: 도서1
book2: 도서2
list: 1권, 2권
-->

0 댓글