관리 메뉴

IT.FARMER

Ajax new XMLHttpRequest() 본문

JavaScript/ajax

Ajax new XMLHttpRequest()

아이티.파머 2011. 3. 4. 19:00
반응형

W3C 권고사항 적용

 

 

/**
 * AjaxUtil 
 * @param url
 * @param methodType   : get 혹은 post
 * @param asynchronous : 동기(true) 비동기(false)
 * @param params
 * @param callbackmethod
 * @param responseType : XML / TEXT / JSON 
 * @returns
 * 
 * @example 
 *    new AjaxUtil(url, methodType, asynchronous, params ,callbackmethod , responseType);
 */
var AjaxUtil = function(url, methodType, asynchronous, params ,callbackmethod , responseType){
    var actionUrl = url;
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 0){
            //UNINITIALIZED :: open()이 아직 호출되지 않은 상태
        }else if(xmlHttp.readyState == 1){
            //LOADING :: send()가 호출되지 않은 상태 (load중)
        }else if(xmlHttp.readyState == 2){
            //LOADED::send() 호출 완료하여 header 와 status 사용이 가능한 상태이며, load완료

        }else if(xmlHttp.readyState == 3){
            //INTERACTIVE :: 일부 data 를 받을 수 있는 상태로 처리중

        }else if(xmlHttp.readyState == "4"){
            //COMPLETE :: 모든 데이터를 받을 수 있는 상태로 완료
        }
        
        if(xmlHttp.status == "200"){
            this.handleResponse(xmlHttp, callbackmethod, responseType);
        }else if(xmlHttp.status == "404"){

        }else if(xmlHttp.status == "500"){

        }
    }
};

if(methodType.toUpperCase() == "GET"){
    xmlHttp.open("get" , actionUrl +"?" + params , asynchronous);
    xmlHttp.send(null);
  
}else if(methodType.toUpperCase() == "POST"){
    xmlHttp.open("POST", actionUrl, asynchronous);

    //Post 방식에서 다음 헤더 지정
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", params.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(params);  //parameter 를 전송
    }
};


AjaxUtil.prototype = {
    handleResponse : function (response, callbackmethod){
    var resJSON = eval('(' + response + ')'); //JSON
    var resXML = response.responseXML;    //XML
    var resText = response.responseText;   //Text 
   
    callbackmethod(response);
  },
  
  uninitialized : function (){//readyState 0
   
  },
  
  open : function (){//readyState 1
   
  },
  
  sent : function (){//readyState 2
   
  },
  
  receiving : function (){//readyState 3
   
  },
  
  loaded : function(){//readyState 4
   
  }
  
};
 
 
반응형

'JavaScript > ajax' 카테고리의 다른 글

Ajax XMLHttpRequest caching 방지  (0) 2011.11.23
Ext Tree Jsp  (0) 2010.10.11
Ajax - Ajax.Request  (0) 2010.08.17
Ajax - Ajax.Updater  (0) 2010.06.09