ajax를 사용함에 있어 매번 xmlHttpRequest객체를 생성하는 코드를 작성하는 것은 비효율적이므로 모듈을 만들어서 임포트 시키는 방법을 써야 한다.
//XMLHttpRequest객체를 생성해 주는 getXMLHttpRequest()함수
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;
}
}
//생성된 XMLHttpRequest객체를 저장할 전역변수
var httpRequest = null;
//XMLHttpRequest객체를 사용해서 지정한방식,지정한 URL, 첨부할 파라미터 값을 사용하여 웹 서버에 요청을 전송
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; //readyState값이 바뀔 때 호출 될 콜백 함수 지정
httpRequest.send(httpMethod == 'POST' ? httpParams : null); //Http요청 방식이 'POST'이면 send()함수를 통해 파라미터 파라미터 전송
}
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;
}
}
//생성된 XMLHttpRequest객체를 저장할 전역변수
var httpRequest = null;
//XMLHttpRequest객체를 사용해서 지정한방식,지정한 URL, 첨부할 파라미터 값을 사용하여 웹 서버에 요청을 전송
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; //readyState값이 바뀔 때 호출 될 콜백 함수 지정
httpRequest.send(httpMethod == 'POST' ? httpParams : null); //Http요청 방식이 'POST'이면 send()함수를 통해 파라미터 파라미터 전송
}