ajax의 가장 기본이자 핵심인 httpRequest,
함수로 만들어서 쓰면 코드를 줄일 수 있습니다.
var
httpRequest=null;
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;
}
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;
httpRequest.send(httpMethod=='POST' ? httpParams : null);
}
사용법
sendRequest("test.jsp", "attr=10&value=안두리", funcReceived, "POST");
function funcReceived() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert(httpRequest.responseText);
}
}
}