Ajax - Ajax의 XMLHTTPRequest 객체 생성의 일반적 루틴

Published on: 2009. 4. 2. 02:24 by louis.dev

<script type="text/javascript">
//1.XMLHTTPRequest 가 생성 되었는지 안되었는지 알아보는 변수를 선언
var xmlRequest = false;

//2.XMLHTTPRequest 가 생성 되었는지 안되었는지 체크하는 실질적 메소드 선언
function ajaxInit() {
 if (xmlRequest == null || !xmlRequest) {
  xmlRequest = getXMLHttpRequest();
 }
}

//3.위의 메소드에서 XMLHTTPRequest 객체가 생성이 안되있으면 getXMLHttpRequest() 를 불러 객체 생성
// 참조:: http://javastore.tistory.com/entry/Ajax-브라우저에-따라-XMLHTTPRequest-객체-생성하기

function getXMLHttpRequest() {
 var request = false;
 try {
   request = new XMLHttpRequest();
 } catch (trymicrosoft) {
   try {
     request = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (othermicrosoft) {
     try {
       request = new ActiveXObject("Microsoft.XMLHTTP");
     } catch (failed) {
       request = false;
     }
   }
 }

 if (!request) {
  alert("Error initializing XMLHttpRequest!");
 }
 return request;
}


</script>