Ajax XMLHttpRequest Object 생성 Util

Published on: 2009.07.13 15:00 by krespo


function getXMLHttpRequest() {
 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;
 }
}
var httpRequest = null;

function sendRequest(url, params, callback, method) {
 httpRequest = getXMLHttpRequest();
 var httpMethod = method ? method : 'GET';
 if (httpMethod != 'GET' && httpMethod != 'POST') {
  httpMethod = 'GET';
 }
 var httpParams = (params == null || params == '') ? null : params;
 var httpUrl = url;
 if (httpMethod == 'GET' && httpParams != null) {
  httpUrl = httpUrl + "?" + httpParams;
 }
 httpRequest.open(httpMethod, httpUrl, true);
 httpRequest.setRequestHeader(
  'Content-Type', 'application/x-www-form-urlencoded');
 httpRequest.onreadystatechange = callback;  //변환작업이 다끝났으면 callback로 넘어간다.
 httpRequest.send(httpMethod == 'POST' ? httpParams : null);    //method가 post 이면 httpParams를 아니면 null을 리턴한다.
}
---------------------------------------------------------------------------------------------------------
사용할 페이지에서
<script type="text/javascript" src="httpRequest.js"></script>
선언하고 사용하면 된다.

Name
Password
Homepage
Secret