본문 바로가기

Programing/Ajax

Ajax - 비동기식?

1)onreadyStatechange - 도착지점(함수설정)
2)readyState - 서버의 수행여부(오류가 나도 4번을 가진다.)
3)status - 서버의 수행여부가 확인되었을때 성공여부
  (200:정상 , 404:파일경로오류 , 405:요청방식오류 , 500:문법오류)
4)responseText
5)responseXML

 

ajaxTest1.html


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">
  // XMLHttpRequest객체는 현재 표준은 아니다. 하지만 대부분의 브라우저에서는
  // 지원을 하고 있다. 그리고 XMLHttpRequest가 W3C의 표준이 아니므로 ie에서는
  // ActiveX컴포넌트형식으로 구현되며, 나머지 크로스 브라우저들은 (FireFox, Safari, Opera...)
  // 들은 native JAvaScript객체로 구현된다. 그러므로 사용자의 브라우저가 무엇인지를 판단하여 XMLHttpRequest객체를
  // 얻어내야한다
 var xhr;
 function createRequest(){ 
  if(window.ActiveXObject)
   xhr = new ActiveXObject("Microsoft.XMLHTTP");
    else if(window.XMLHttpRequest)
     xhr = new XMLHttpRequest();
 }
 
 function test(){
  createRequest(); //함수 호출로 사용자의 브라우저를 판단한후 XMLHttpRequest객체를 얻어내었다.
  xhr.onreadystatechange = res; //서버에서 응답이 전달될때 그 응답을 받을 함수  
  xhr.open("get","ajaxTest1.jsp",true); //요청방식과 요청할 페이지 , 그리고 비동기식 설정을 한것이다.
  xhr.send(null); //서버 요청 수행 "get" 방식일 때만 null
  document.all.txt.value="동기식과 비동기식 연습";
 }
 function res(){
  if(xhr.readyState == 4) //서버 데이터 처리가 완료된 경우 : 4
   if(xhr.status == 200){ //정상적인 완료 : 200
    var str = xhr.responseText; // 응답 문자열
    alert(str);
   }  
 }
</script>
</head>
<body>
 <input type="button" value="Test" onClick="test()"><br>
 <textarea rows="5" cols="30" id="txt"></textarea>
</body>
</html>



ajaxTest1.jsp


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript">
  // XMLHttpRequest객체는 현재 표준은 아니다. 하지만 대부분의 브라우저에서는
  // 지원을 하고 있다. 그리고 XMLHttpRequest가 W3C의 표준이 아니므로 ie에서는
  // ActiveX컴포넌트형식으로 구현되며, 나머지 크로스 브라우저들은 (FireFox, Safari, Opera...)
  // 들은 native JAvaScript객체로 구현된다. 그러므로 사용자의 브라우저가 무엇인지를 판단하여 XMLHttpRequest객체를
  // 얻어내야한다
 var xhr;
 function createRequest(){ 
  if(window.ActiveXObject)
   xhr = new ActiveXObject("Microsoft.XMLHTTP");
    else if(window.XMLHttpRequest)
     xhr = new XMLHttpRequest();
 }
 
 function test(){
  createRequest(); //함수 호출로 사용자의 브라우저를 판단한후 XMLHttpRequest객체를 얻어내었다.
  xhr.onreadystatechange = res; //서버에서 응답이 전달될때 그 응답을 받을 함수  
 
  var str = document.all.movie.value;
   if(str == "") //사용자가 영화 제목을 입력하지 않았다면 더이상 수행을 하지 않는다.
    return;
   
  var param = "movie="+escape(encodeURIComponent(str)); //한글처리
 
  xhr.open("get","ajaxTest2.jsp?"+param,true); //요청방식과 요청할 페이지 , 그리고 비동기식 설정을 한것이다.  
  xhr.send(null); //서버 요청 수행 "get" 방식일 때만 null
 
 
 }
 function res(){
  if(xhr.readyState == 4) //서버 데이터 처리가 완료된 경우 : 4
   if(xhr.status == 200){ //정상적인 완료 : 200
    var str = xhr.responseText; // 응답 문자열
    alert(str);
   }else
    alert("실패 : " + xhr.status + ":" +xhr.responseText);
 }
</script>
</head>

<body>
 영화제목 : <input type="text" id="movie"><br>
 <input type="button" value="Test" onClick="test()"><br><br><br>
 
</body>

</html>



ajaxTest2.jsp


<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
 String m = URLDecoder.decode(request.getParameter("movie"),"utf-8");
 String msg = null;
 if(m.startsWith("태극기"))
  msg = m + "는(은) 반공영화!";
 else if(m.startsWith("헤리포터"))
  msg = m + "는(은) 판타지";
 else if(m.startsWith("A"))
  msg = m+"는(은) SF";
 else
  msg = m+"는(은) 모르는 영화";
%>
<%=msg %>


결과

사용자 삽입 이미지


 

'Programing > Ajax' 카테고리의 다른 글

Ajax - suggest  (0) 2008.07.29
Ajax - DB 값 빼오기  (0) 2008.07.29
Ajax - innerHTML  (0) 2008.07.29
Ajax - innerHTML  (0) 2008.07.29
Ajax - Ajax(dwr)와 iBatis를 사용해서 DB에서 정보 가져오기  (0) 2008.07.29