ajax 기본정리

ajax 기본정리

 

간단한 ajax를 만들어보았다.

 

겟 방식과 포스트 방식 각각으로, index.jsp 안에 result.jsp를 비동기적(어싱크로노우스)으로 뿌릴 수 있다.

 

index.jsp

<%@ page language=”java” contentType=”text/html; charset=EUC-KR”
    pageEncoding=”EUC-KR”%>
<!DOCTYPE html>
<html>
<head>
<meta charset=”EUC-KR”>
<title>Insert title here</title>

     <script src=”myajax.js” type=”text/javascript”></script>
     <script type=”text/javascript”>

     //자바스크립트 쓰는곳

     </script>

</head>
<body>
  <form name=”frm”>
 <input type=”text” name=”txt1″ value=”id=admin”>
 <a href=”javascript:sendPost(document.frm.txt1.value)”>포스트로 보내기</a>
 <a href=”javascript:sendGet(document.frm.txt1.value)”>겟으로 보내기</a>
 <div id=”result”></div>
  </form>
</body>
</html>

 

myajax.js

var httpRequest=null;//통신객체(각 브라우저에 내장)

 

function createHttpRequest(){
  if(window.ActiveXObject) //IE
  { return new ActiveXObject(“Msxml2.XMLHTTP”); }

  else if(window.XMLHttpRequest) //크롬,파이어폭스
  { return new XMLHttpRequest(); }

  else //지원하지 않는 브라우저
  { return null; }
}

 

function sendPost(pValue){
  httpRequest=createHttpRequest();
  httpRequest.open(“POST”,”result.jsp”,true);
  httpRequest.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded”);
  httpRequest.send(pValue); //id=aaa&pwd=1234
  httpRequest.onreadystatechange=pResult;
 /*
 1. 객체를 얻어온다.
 2. open: 서버 연결. (메소드 방식,연결하는 타입명,true(=비동기))
 3. 한글 변환(POST만 할것)
 4. send: 데이터 전송. 예를 들어 포스트 방식은 여기에 id=aaa&pwd=1234라고 쓰고, get방식은 null을 줘야한다. (get방식은 open의 url안에 써야함)
 5. onreadystatechange: 서버로부터 응답이 들어오면 메소드 호출한다.
 */
}

 

function sendGet(pValue){
  httpRequest=createHttpRequest();
  httpRequest.open(“GET”,”result.jsp?”+pValue,true); //id=aaa&pwd=1234
  httpRequest.send(null);
  httpRequest.onreadystatechange=pResult;
}

 

function pResult(){
  if(httpRequest.readyState==4){
   if(httpRequest.status==200){
      var div=document.getElementById(“result”); //$(‘#result’).text() 와 같음
      div.innerHTML=httpRequest.responseText;
      //위 두 줄을 $(‘#result’).html(httpRequest.responseText)로 대체 가능
   }
  }
}

 

/*readyState
0: uninitialized : 객체만 생성되고 아직 초기화 되지 않은 상태
1: loading : open 메서드가 호출되고 아직 send 메서드가 불리지 않은 상태
2: loaded : send메소드가 불렸지만 status 와 헤더는 도착하지 않은 상태
3: interactive : 데이터의 일부를 받은 상태
4: completed :  데이터를 전부 받은 상태, 완전한 데이터 이용가능

 

status
200 : ok 요청성공
403 : Forbidden  접근거부
404 : not found  페이지 없음
500 : internal server error 서버오류 발생*/

 

result.jsp

<%@ page language=”java” contentType=”text/html; charset=EUC-KR”
    pageEncoding=”EUC-KR”%>
<!DOCTYPE html>
<html>
<head>
<meta charset=”EUC-KR”>
</head>
<body>
 
    <input type=”text” value=”값”>
 
</body>
</html>