XMLHttpRequest 알아보기.

ITWeb/개발일반 2011. 11. 16. 15:20
[참고사이트]


[XMLHttpRequest 생성하기]

- xhr = new XMLHttpRequest();

  . 이제는 일반적으로 이넘으로 사용을 하자.

- xhr = new ActiveXObject("Microsoft.XMLHTTP");
  . IE5, 6을 지원하기 위한건데.. 이제 이넘들은.. 버리죠.. :) 


[XMLHttpRequest Interface 알아보기]
- Level2 에 있는 Interface 정보를 긁어온 내용입니다.
[NoInterfaceObject]
interface XMLHttpRequestEventTarget : EventTarget {
  // event handlers
           attribute Function onloadstart;
           attribute Function onprogress;
           attribute Function onabort;
           attribute Function onerror;
           attribute Function onload;
           attribute Function ontimeout;
           attribute Function onloadend;
};

interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {

};

[Constructor]
interface XMLHttpRequest : XMLHttpRequestEventTarget {
  // event handler
           attribute Function onreadystatechange;

  // states
  const unsigned short UNSENT = 0;
  const unsigned short OPENED = 1;
  const unsigned short HEADERS_RECEIVED = 2;
  const unsigned short LOADING = 3;
  const unsigned short DONE = 4;
  readonly attribute unsigned short readyState;

  // request
  void open(DOMString method, DOMString url);
  void open(DOMString method, DOMString url, boolean async);
  void open(DOMString method, DOMString url, boolean async, DOMString? user);
  void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password);
  void setRequestHeader(DOMString header, DOMString value);
           attribute unsigned long timeout;
           attribute boolean withCredentials;
  readonly attribute XMLHttpRequestUpload upload;
  void send();
  void send(ArrayBuffer data);
  void send(Blob data);
  void send(Document data);
  void send([AllowAny] DOMString? data);
  void send(FormData data);
  void abort();

  // response
  readonly attribute unsigned short status;
  readonly attribute DOMString statusText;
  DOMString getResponseHeader(DOMString header);
  DOMString getAllResponseHeaders();
  void overrideMimeType(DOMString mime);
           attribute DOMString responseType;
  readonly attribute any response;
  readonly attribute DOMString responseText;
  readonly attribute Document responseXML;
};

[Constructor]
interface AnonXMLHttpRequest : XMLHttpRequest {
};

[XMLHttpRequest 구현 알아보기]
- 참고링크 
 
. header filed : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 

# 기본 XMLHttpRequest 구현체
<script type="text/javascript">
//<![CDATA[

var XHR = {

conn:null,

request:{

url:'',

method:'GET',

data:'',

async:true

},

header:{

key:[],

value:{}

},

data:{

key:[],

value:{}

},

response:{

type:"XML"

},

createConnection:function () {

if ( typeof window.XMLHttpRequest ) {

this.conn  = new XMLHttpRequest();

} else if ( typeof window.ActiveXObject ) {

this.conn = new ActiveXObject("Microsoft.XMLHTTP");

}

return this.conn;

},

createRequestData:function () {

var size = this.data.key.length;

for ( var i=0; i<size; i++ ) {

this.request.data += this.data.key[i] + '=' + this.data.value[this.data.key[i]] + '&';

}

this.request.data = this.request.data.substr(0, this.request.data.length - 1);

return this.request.data;

},

createRequestHeader:function () {

var size = this.header.key.length;

for ( var i=0; i<size; i++ ) {

this.conn.setRequestHeader(this.header.key[i], this.header.value[this.header.key[i]]);

}

},

open:function () {

var requestUrl;

if ( this.request.method == 'GET' ) {

requestUrl = this.request.url + '?' + this.request.data;

} else {

requestUrl = this.request.url;

}

this.conn.open(this.request.method, requestUrl, this.request.async);

},

send:function () {

if ( this.request.method == 'GET' ) {

this.conn.send();

} else {

this.conn.send(this.request.data);

}

}

}

//]]>
</script> 


# Client 페이지
<!DOCTYPE html>

<html>

<head>

<title>XMLHttpRequest</title>


<script type="text/javascript">

//<![CDATA[

XHR.request.url = "http://192.168.1.1/api/request/index.html";

XHR.request.method = "GET"; // "POST";

XHR.header.key = ["Content-Type"];

XHR.header.value = {

"Content-Type":"application/x-www-form-urlencoded"

};

XHR.data.key = ["id", "s", "ts"];

XHR.data.value = {

    "id":12345678,

    "s":"320x48",

    "ts": Math.floor(new Date().getTime()/1000)

};
 

function xhrRequest() {

XHR.createConnection();

XHR.createRequestData();

/*

response event 처리를 위해서 별도로 수행해야 하는 함수를 추가 작성함.
각 biz 특성에 맞는 기능 구현. 

*/ 

XHR.conn.onreadystatechange = function () {

switch ( XHR.conn.readyState ) {

case 0 : // XHR.conn.UNSENT :

break;

case 1 : // XHR.conn.OPENED :

break;

case 2 : // XHR.conn.HEADERS_RECEIVED :

break;

case 3 : // XHR.conn.LOADING :

break;

case 4 : // XHR.conn.DONE :

doReadyStateChange();

break;

}

function doReadyStateChange() {

if ( XHR.conn.status >= 200 && XHR.conn.status < 300 ) {

testConsole(XHR.conn.responseXML.getElementsByTagName("cid")[0].childNodes[0].nodeValue);

} else if ( XHR.conn.status == 404 ) {

alert('Not Found.');

} else {

alert(XHR.conn.status);

}

};


XHR.open();

XHR.createRequestHeader();

XHR.send();

}


function testConsole (log) {

var console = document.getElementById("console");

console.innerHTML = log + '<br>' + console.innerHTML;

}

//]]>

</script> 

</head>

<body>

<button onclick="xhrRequest();">XMLHttpRequest Call</button>

<div id="console" style="width:800px; height:400px"></div>

</body>

</html> 


# index.html 에서 return 해주는 XML
<?php

header('Content-Type: text/xml; charset=utf-8');

?>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<result>

    <item>

        <cid>1234567890</cid>
        <name>Henry</name> 

    </item>

</result>



여기까지 아주 기본적인 구현을 해봤습니다.
넘겨 받은 XML 값에 대한 parser 는 위에서 처럼 DOM 을 이용해서 할 수도 있고, jquery 같은 라이브러리를 이용해서도 쉽게 할 수 있습니다.

XML Parser 관련해서는 혹시나 해서 예전에 작성해 놓은 글 링크 합니다.
http://jjeong.tistory.com/385

위에 작성된 코드는 말 그대로 Spec 문서에 기초해서 작성한 것입니다.
이와 관련해서 HTML5 에서 제공하는 WebSocket 도 알아 놓으면 좋겠다.
http://jjeong.tistory.com/485







: