프로그래밍 언어/JavaScript

[JavaScript] JavaScript XML Parsing ( new XMLHttpRequest() )

반응형

예제코드

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<p id='demo'></p>

<script type="text/javascript">
let xhttp = new XMLHttpRequest(); //XML 통신을 하기 위한 것 (요청)

xhttp.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
        //alert(this.responseXML);
        nodeValFunc( this );
    }    
}
xhttp.open("GET", "member.xml", true);
xhttp.send();

function nodeValFunc( xml ) {
    let num, name;
    let txt, numtxt, xmlDoc;

    txt = numtxt = '';

    xmlDoc = xml.responseXML; //위에서 this를 통해서 넘겨 받음

    num = xmlDoc.getElementsByTagName("번호");
    name = xmlDoc.getElementsByTagName('이름');
    console.log(num.length);

    for(let i=0; i < num.length; i++){
        txt += num[i].childNodes[0].nodeValue + "<br>";
        numtxt += name[i].childNodes[0].nodeValue + "<br>";

        /*
        num을 통해서 [i]..
        번호라는 태그 안에 태그가 없기 때문에 0번째를 통해서 가져오는것이다.
        */
    }

    document.getElementById('demo').innerHTML = txt + numtxt;
}
</script>

</body>
</html>

XML문서

<?xml version="1.0" encoding="UTF-8"?>
<고객들>
    <고객>
        <번호>1</번호>
        <이름>홍길동</이름>
        <주소>서울시</주소>
        <방문>2020/03/23</방문>
    </고객>
    <고객>
        <번호>2</번호>
        <이름>성춘향</이름>
        <주소>남원시</주소>
        <방문>2021/01/31</방문>
    </고객>
    <고객>
        <번호>3</번호>
        <이름>일지매</이름>
        <주소>부산시</주소>
        <방문>2019/07/11</방문>
    </고객>
</고객들>

let xhttp = new XMLHttpRequest();

통신 하기 위해서는 객체가 필요하다

 

순서

함수 -> open -> send -> 함수 요청

 

readyState : 진행 상태
0 -> open 메소드를 수행하기 전 상태
1 -> loading 중.....
2 -> loading 완료
3 -> Server 처리중
4 -> Server 처리 완료

 

status : 상태
200 -> 성공(success)
403 -> 접근금지
404 -> 없음. 못찾는 경우. ex) test.txt가 없는 경우
500 -> 구문에러(문법 에러)

 

responseText 다 읽었을때 txt를 불러오는 것

 

if(this.readyState == 4 && this.status == 200){
            nodeValFunc( this );
}

 

진행 상태 : 처리완료 && 상태 : 성공 일때 xhttp.responseXML( =this ) 을 전달!

 

num = xmlDoc.getElementsByTagName("번호");

num 이라는 변수에 모든 "번호" tag 값을 전달


각 propety 참고 : http://tcpschool.com/ajax/ajax_server_response

반응형