이 블로그 검색

2010년 9월 7일 화요일

ajax 기본

 function createXMLHttpRequest(){
 try{return new ActiveXObject("Msxml2.XMLHTTP");}catch(e){}
 try{return new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}
 try{return new XMLHttpRequest();}catch(e){}
 alert("XMLHttpRequest not supported");
 return null;
}

function $(id){return document.getElementById(id);}





window.onload = function (){
  var xhr =createXMLHttpRequest();
  xhr.onreadystatechange= function(){
     if(xhr.readyState!=4){return;}//요청이 완료되지않았으면 return;
      if(xhr.status!=200){
        //에러처리, 예를 들어 에러 메시지를 화면에 보여준다.
        return; 
     }
     $("sandbox").innerHTML="Retrieved from server...";
     $("sandbox").innerHTML+=xhr.responseText;
  };
  xhr.open("GET", "message.html", true);
  xhr.send(null);
};




##설명
message.html의 내용을 가져와서 본문에 뿌려준다.
xhr.open("GET", "message.html", true)에서 true는 비동기적 호출이란 뜻이다.
xhr.send(null)에서 null은 요청시 본문이 없다는 뜻이다.
same-domain policy : XMLHttpRequest는 오로지 동일한 서버의 컨텐츠에만 접근할 수 있다.

댓글 없음:

댓글 쓰기