!----------------------------- commFunction.js ------------------------
function createXMLHttpRequest() { var reqHttp; if (window.ActiveXObject) { // internet explorer일 경우 try { reqHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { reqHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e1) { reqHttp = null; } } } else if (window.XMLHttpRequest){ // internet explorer가 아닐경우 try { reqHttp = new XMLHttpRequest(); } catch (e) { reqHttp = null; } } if (reqHttp == null) errorMessage(); //XMLHttpRequest 생성을 실패했을경우 return reqHttp; }
// 지원할 수 없는 브라우저 사용 function errorMessage() { alert!("XMLHttpRequest를 지원하지 않는 브라우저입니다."); }
function openServer(method, func, file){ var xmlHttp = createXMLHttpRequest(); //XMLHttpRequest 객체의 생성 xmlHttp.open(method, file, true); //전송방식, URL, 동기 혹은 비동기(true) xmlHttp.[안내]태그제한으로등록되지않습니다-[안내]태그제한으로등록되지않습니다-onreadystatechange = function(){ //readyState상태의 변경시 이벤트 발생 if(xmlHttp.readyState == 4){ //서버 데이터 처리가 완료된경우 4 if(xmlHttp.status == 200){ //정상적으로 처리되었을경우 200 func(xmlHttp) //클라이언트에서의 처리 } } } xmlHttp.send(null); //서버에게 데이터 전송. GET방식일 경우 null이다. }
!---------------------------------- test.html --------------------------- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- httpXMLRequest를 생성하고 콜백함수를 호출하는 commFunction.js를 포함한다. --> <script src="commFunction.js"></script> <script>
function printFileInfo(xmlHttp){ var xmlData = xmlHttp.responseXML; var entertainer = xmlData.getElementsByTagName("entertainer");
for(var i=0; i<entertainer.length; i++) { var age = entertainer[i].childNodes[0].childNodes[0].nodeVal!ue; var name = entertainer[i].childNodes[1].childNodes[0].nodeVal!ue; insertRow(age, name); //테이블에 row추가 } }
function insertRow(age, name) { var oTable = document.getElementById("resultTable").children[0]; var oRow = document.createElement("tr"); var oCel1 = document.createElement("td"); var oCel2 = document.createElement("td"); //table, tr, td 객체 생성
oRow.style.textAlign='center'; oRow.appendChild(oCel1); oRow.appendChild(oCel2); oCel1.innerHTML = age; oCel2.innerHTML = name;
oTable.appendChild(oRow); //만들어진 row객체 테이블에 추가 } </script> </head>
<body> <input type="button" value="전송" [안내]태그제한으로등록되지않습니다-xx[안내]태그제한으로등록되지않습니다-xxonClick="openServer('GET', printFileInfo, 'oracleJava.xml')" / > <!--param : 전송방식, 함수명, 파일명--> <table id="resultTable" border="1"> </table>
</body> </html>
!----------------------------------------------------------------------------- 바로 아래의 계시글과 같은내용이지만 이처럼 공통으로 사용하는부분을 js파일로 묶어서 정송방식, 함수명, 파일을 파라미터로 주고 사용하면 훨씬 수월합니다. 필요하다면 동기, 비동기방식, post방식일경우 서버로 보낼 데이터도 param으로 추가한 후 사용할수 있습니다. 앞으로의 강좌는 위의 commFunction을 사용하겠습니다. | |