Daily Pogle

[Javascript] XML 활용하기(XMLHttpRequest) 본문

Programming language/Javasript

[Javascript] XML 활용하기(XMLHttpRequest)

pogles 2023. 2. 1. 15:58

XML API 관련 사이트(참고)

 

XMLHttpRequest - Web APIs | MDN

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.

developer.mozilla.org

XML API 공식문서

 

XMLHttpRequest Standard

Abstract The XMLHttpRequest Standard defines an API that provides scripted client functionality for transferring data between a client and a server. Table of Contents 1 Introduction 1.1 Specification history 2 Terminology 3 Interface XMLHttpRequest 3.1 Con

xhr.spec.whatwg.org

W3S - XMLHttpRequestObject

 

AJAX The XMLHttpRequest Object

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com


개요

 

XMLHttpRequest 객체를 서버와 상호작용하기 위해 사용되는 API 이다. 페이지를 새로고침하지 않아도 URL를 통해 데이터를 가져올 수 있어, 사용자의 작업을 방해하지 않고 페이지를 업데이트 할 수 있다는 장점이 있다.

 

XMLHttpRequest 는 AJAX 와 크게 관련있어서 AJAX 사용 시 많이 활용되는 API 이다. 이름에서 볼 수 있듯이 XML를 다룰 수 있으며, XML 뿐만 아니라 모든 데이터를 다룰 수 있다.

 

모든 현대 브라우저에서 XMLHttpRequest 를 지원하고 있다.

 


XMLHttpRequest API 활용하기

 

 

1. XMLHttpRequest()

  • XML 정보를 포함한 다양한 정보를 담을 수 있는 XHR 객체생성.
let xhttp;
xhttp = new XMLHttpRequest();

 

2. XMLHttpRequest.readystate

  • XHR client 의 현재 상태를 반환
  return (state) description
  0 open 함수 수행 전 request 만들어지기 전.
  1 open 함수 수행 후 server에 request 보내는중.
  2 server 에서 request 받음.
  3 server 에서 request 에 대한 처리 중
  4 request 종료 후 response 받을 수 있음. 

 

 

3. XMLHttpRequest.state

  • XMLHttpRequest 에 대해 server 의 response 에 대한 Http 상태코드 반환
  return (http state code) description
  200 접근성공(Success)
  403 접근금지(Forbidden)
  404 URL 없음, 탐색실패(Not Found)
  500 구문에러, 문법틀림(Syntax Error)

 

 

4. XMLHttpRequest.onreadystatechange

  • onreadystatechage 는 event handler 이다. readystate가 change 되면 나타나는 handler.
  • event 발생 시 뒤에 작성한 콜백함수를 호출한다.
let xhttp; 
xhttp = new XMLHttpRequest(); // XHR 객체 생성.
xhttp.onreadystatechange = function () {
    // server로부터 정상적으로 받았으면 fillNodeFunc 함수 실행.
    if(this.readyState == 4 && this.status == 200) fillNodeFunc( xhttp );
}

 

 

5. XMLHttpRequest.open()

  • request 새로 생성하거나 재생성하는 함수
  • 인자 (method, url, async, user, password)
  • open() 을 통해 request 생성하고, send()를 통해 server로 request 를 보냄. 
인자 인자
method GET, POST, PUT, DELELE async (동기화유무) true, false
url request 할 url user, password 인증 필요시 (default = null)

 

6. XMLHttpRequest.send()

  • request 를 server 로 보내는 함수.

 

7. XMLHttpRequest.responseXML

  • request 를 통해 받아온 정보(HTML/XML) 를 XML DOM 형태로 반환.
let xhttp; 
xhttp = new XMLHttpRequest(); // XHR 객체 생성. (정보저장할 객체))
xhttp.onreadystatechange = function () {  // XHR 상태가 변할때마다 (request 보낸 이후 완료될 때까지 변경됨)
    if(this.readyState == 4 && this.status == 200) { // server로부터 정상적으로 받았으면(완료되었으면) 실행.
        let xmlDoc;
        xmlDoc = xhttp.responseXML; // XML 불러오기, XML 내용담음. XML DOM 객체
    }
}
xhttp.open("GET", "book.xml", true);
xhttp.send();

 

 

8. XMLHttpRequest.responseXML

  • request 를 통해 받아온 정보(HTML/XML 등) 를 string 형태로 반환.
let xhttp; 
xhttp = new XMLHttpRequest(); // XHR 객체 생성. (정보저장할 객체))
xhttp.onreadystatechange = function () {  // XHR 상태가 변할때마다 (request 보낸 이후 완료될 때까지 변경됨)
    if(this.readyState == 4 && this.status == 200) { // server로부터 정상적으로 받았으면(완료되었으면) 실행.
        let xmlStr;
        xmlStr = xhttp.responseText; // XML 불러오기, XML 내용담음. string 으로 반환
    }
}
xhttp.open("GET", "book.xml", true);
xhttp.send();

 


XMLHttpRequest를 통해 받은 XML 접근하기

 

W3C XML DOM 표준에 따르면 XML 문서 내의 모든 것은 노드(node) 라고 불리는 계층적 단위에 정보를 담고 있음

XML 를 활용하기 위해서는 W3C XML DOM의 노드(node) 에 대해 잘 알아야한다.

 

노드 설명
document node XML 문서 전체를 나타내는 노드.
element node 모든 XML 요소가 element node, attribute node를 가질 수 있는 node.
attribute node XML 요소의 속성이 모두 attribute node, element node 에 대한 정보를 가지고 있는 node.

하지만 element node 의 자식노드는 아님.
text node XML 문서 내 텍스트가 모두 text node.
comment node XML 문서 내 주석이 모두 comment node.

 

활용하기

 

xml 파일 예시

더보기
<?xml version="1.0" encoding="UTF-8"?>


<books>
	<book>
		<title>가나다라마바사</title>
		<author>김세종</author>
		<date>2021/2/21</date>
		<price>20000</price>
	</book>
	<book>
		<title>정치학의 이해</title>
		<author>김우태</author>
		<date>2015/1/7</date>
		<price>34000</price>
	</book>
	<book>
		<title>현대동남아의 이해</title>
		<author>홍길동</author>
		<date>2016/12/23</date>
		<price>17800</price>
	</book>
	<book>
		<title>국제정세의 이해</title>
		<author>김연세</author>
		<date>2020/5/1</date>
		<price>20000</price>
	</book>
	<book>
		<title>신호와 시스템의 이해</title>
		<author>김물리</author>
		<date>2020/6/15</date>
		<price>42000</price>
	</book>
</books>
xmObj = xhttp.responseXML; // XML DOM

 

 

   
xmlObj.documentElement xml 문서전체(전체노드) 반환
xmlObj.documentElement.childNodes xml 의 자식노드 리스트 반환 : <book> 태그들
node = xmlObj.documentElement.childNodes[2];
nextSibling = node.nextSibling;
preSibling = node.previousSbling;
node = xml 의 세번째 자식노드
nextSibling = node 의 다음형제노드 (xml 의 네번째 자식노드)
preSibling = node 의 이전형제 노드 (xml 의 두번째 자식노드
parentnode = babynode.parentNode; parentnode = babynode 의 부모노드