'httpRequest 객체 모듈화 하기'에 해당되는 글 1건

  1. 2009.12.03 httpRequest 객체 모듈화 하기
반응형

------------------------------------------------------
window.onload = function(){
 loadBooks();
}

function loadBooks(){
 //sendRequest("books.jsp",null,loadedBooksXML,"GET");
 new ajax.xhr.Request("books.jsp",null,loadedBooksXML,"GET");
 new ajax.xhr.Request("books.xsl",null,loadedBooksXSL,"GET");
}

var xmlDoc = null;
var xslDoc = null;


function loadedBooksXML(req) {
 if (req.readyState == 4) {
  if (req.status == 200) {
   xmlDoc = req.responseXML;
   //sendRequest("books.xsl",null,loadedBooksXSL,"GET");
   //doXSLT(); 
  }
 }
}

function loadedBooksXSL(req) {
 if (req.readyState == 4) {
  if (req.status == 200) {
   xslDoc = req.responseXML;
   doXSLT();
  }
 }
}

function doXSLT(){
 if(xmlDoc == null || xslDoc == null) return;
 var bookList = document.getElementById("bookList");
 if(window.ActiveXObject){ // IE방식의 xml문서를 xsl 변환
  bookList.innerHTML = xmlDoc.transformNode(xslDoc);
 }else{ // W3C 지원 브라우저의 xml문서를 xsl변환
  var xsltProc = new XSLTProcessor();
  xsltProc.importStylesheet(xslDoc);
  var fragment = xsltProc.transformToFragment(xmlDoc,document);
  bookList.appendChild(fragment);
 }
}
---------------------------------------------------

var ajax = {};
ajax.xhr = {};

ajax.xhr.Request = function(url,params,callback, method){
 this.url = url;
 this.params = params;
 this.callback = callback;
 this.method = method;
 this.send();
}

ajax.xhr.Request.prototype = {
 getXMLHttpRequest: function(){
  if(window.ActiveXObject){
   try{
    return new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
    try {
     return new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e1) {
     return null;
    }
   }
  }else if(window.XMLHttpRequest){
   return new XMLHttpRequest();
  }else{
   return null;
  }
 },

 send: function() {
  this.req = this.getXMLHttpRequest();
  var httpMethod = this.method ? this.method : 'GET';

  if(httpMethod != 'GET' && httpMethod != 'POST'){
   httpMethod = 'GET';
  }

  var httpParams = (this.params == null || this.params == '')? null : this.params;
  var httpUrl = this.url;

  if(httpMethod == 'GET' && httpParams != null){
   httpUrl = httpUrl + "?" + httpParams;
  }

  this.req.open(httpMethod, httpUrl, true);
  this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  var request = this;
  this.req.onreadystatechange = function(){
   request.onStateChange.call(request);
  }
  this.req.send(httpMethod == 'POST' ? httpParams : null);
 },

 onStateChange: function(){
  this.callback(this.req);
 }
}

Posted by 1010