'XMLHTTPRequest'에 해당되는 글 3건

  1. 2011.11.16 XMLHttpRequest 알아보기.
  2. 2010.05.11 XMLHttpRequest javascript 용 class v1.0.0
  3. 2008.03.21 XMLHttpRequest Level 2

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







:

XMLHttpRequest javascript 용 class v1.0.0

ITWeb/개발일반 2010. 5. 11. 12:26
여기 저기 널린 코드들은 많은데 맘에 드는 코드가 별로 없어서 기냥 만들었습니다.
도대체 코드를 보기 힘들게 작성하는 이유는 무슨 심리 인지.. 좀 쉽게 작성 하면 어디 덧나나.. ㅡ.ㅡ;;
참고 사이트 : http://www.w3.org/TR/XMLHttpRequest/

뭐 아래 코드가 잘 짜진것도 아니지만.. 보기 쉽게 하려고 쬐금 노력은 했다는.. ㅎㅎ
이것도 보기 힘들다면.. 패스~



/*
 * XMLHttpRequest Control Module
 *
 * @package
 * @path
 * @filename    xhr.js
 * @author      
 * @date        2010/05/03
 *
 * Change History
 * Date         Engineer                Type        Description
 * ----------   ------------------      ---------   --------------------
 * 2010/05/03 Henry Jeong  create  initialize
 */
/*
 *
 * XMLHttpRequest module object
 *
 */
var JXhr = function() {
};
/*
 *
 * xmlhttprequest variables
 */
JXhr.prototype.vars = {
 xhr : null,
 onreadystatechange : null,
 onload : null,
 onerror : null,
 onresponse : null,
 contenttype : "text/xml",
 overridemimetype : "text/xml",
 method : "GET",
 callUrl : "",
 async : true,
 header : [], // setRequestHeader
 responsedata : "XML", // responseText, responseXML
 params : ""
}
JXhr.prototype.init = function() {
 if (window.XMLHttpRequest) {
  JXhr.vars.xhr = new XMLHttpRequest();
  JXhr.vars.xhr.onreadystatechange = JXhr.vars.onreadystatechange;
 } else if (window.ActiveXObject) {
  try {
   JXhr.vars.xhr = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e) {
   JXhr.vars.xhr = false;
  }
  if (JXhr.vars.xhr) {
   JXhr.vars.xhr.onreadystatechange = JXhr.vars.onreadystatechange;
  }
 }
}
JXhr.prototype.open = function() {
 var openUrl = JXhr.vars.callUrl;
 if (JXhr.vars.method == "GET") {
  if (JXhr.vars.params != "") {
   openUrl += "?" + JXhr.vars.params;
  }
 }
 JXhr.vars.xhr.open(JXhr.vars.method, openUrl, JXhr.vars.async);
}
JXhr.prototype.send = function() {
 switch (JXhr.vars.method) {
 case "GET":
  JXhr.vars.xhr.send(null);
  break;
 case "POST":
  JXhr.vars.xhr.setRequestHeader("Content-type",
    "application/x-www-form-URLencoded");
  JXhr.vars.xhr.setRequestHeader("Content-length",
    JXhr.vars.params.length);
  JXhr.vars.xhr.setRequestHeader("Connection", "close");
  JXhr.vars.xhr.send(JXhr.vars.params);
  break;
 }
}
JXhr = new JXhr();
/*
 * <script type="text/javascript"> <!-- function getReadyStateChage () { if (
 * JXhr.vars.xhr.readyState == 4 ) { if ( JXhr.vars.xhr.status == 200 ||
 * JXhr.vars.xhr.statusText == "OK" ) { JXhr.vars.onresponse(); } else {
 * document.getElementById("divDebug").innerHTML = JXhr.vars.xhr.statusText + "<br>" +
 * document.getElementById("divDebug").innerHTML; } } }
 *
 * function getResponseData () { if ( JXhr.vars.responsedata == "XML" ) {
 * JXhr.vars.xhr.responseXML; } else { JXhr.vars.xhr.responseText; } }
 *
 * function run() { JXhr.vars.onreadystatechange = getReadyStateChage;
 * JXhr.vars.onresponse = getResponseData; JXhr.vars.method = "GET";
 * JXhr.vars.callUrl = "http://HOSTNAME/test.txt";
 * JXhr.vars.async = true; JXhr.vars.responsedata = "TEXT"; JXhr.vars.params =
 * "";
 *
 * JXhr.init(); JXhr.open(); JXhr.send(); } //--> </script>
 */

:

XMLHttpRequest Level 2

ITWeb/스크랩 2008. 3. 21. 18:04

ref. http://www.w3.org/TR/2008/WD-XMLHttpRequest2-20080225/

w3c 에서 2월 25일에 올라온 겁니다.

이건 기본적으로 필요로 하는 환경이 DOM2Event, DOM3Core, HTML5 에서 정상 작동 합니다.
못보던 method 들도 있고 cross-site access request 에 대해서도 지원이 되는듯 하내요..
참고. http://www.w3.org/TR/access-control/

그리고 예전에는 status 를 계속 확인해야 했었지만.. 지금은.. event 를 지원해 주고 있어서 코딩 하기 좀더 쉬워진 느낌 이내요.

원문을 저도 다 읽어 보지는 못하고 그냥 훑어 본거라.. 관심 있으신 분들은.. 한번 읽어 보세요.. ^^*

T.G.I.F

: