Java, Spring/14일
14일차 6 - Ajax test2
Caprica Six
2012. 9. 20. 09:42
Ajax test2
msg.jsp : plain type으로 만들어서 data로만 쓰여
<%@ page language="java" contentType="text/plain; charset=UTF-8" %> 성형은 신을 용서하는 인간의 행위이다.
msg.txt
실수란 신을 용서하는 인간의 행위이다.
ajax_js.test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> <script> function load(url) { var xmlHttp = createXMLHttpRequest(); xmlHttp.open("GET", url, true); //true:비동기방식 //false:동기방식(일부 브라우저에선 동작안해) //onreadystatechange : // readystate 바뀔때마다 function()이 동작되게함(callback함수지) xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4 ) { /* readyState값 (받을때 어느단계까지 수행되었는가) 0 : uninitialized. XMLHttpRequest객체만 생성되고 아직 초기화 되지 않은 상태 1 : loading. open 메서드가 호출되고 아직 send 메서드가 불리지 않은 상태 2 : loaded. send 메서드가 불렸지만 status와 헤더는 도착하지 않은 상태 3 : interactive. 데이터의 일부를 받은 상태(받고 있는 중) 4 : completed. 데이터를 전부 전송받은 상태 */ if (xmlHttp.status == 200) { /* status값 (정상적인 수행이 되었는가) 200 : OK. 요청 성공 403 : Forbidden. 접근 거부 404 : Not Found. 페이지 없음 500 : Internal Server Error. 서버오류 발생 */ process(xmlHttp); } else { alert(xmlHttp.status); } } } xmlHttp.send(null); //GET방식이니까 null //POST방식이면 body를 실어야지 } function createXMLHttpRequest() { var xmlHttp = null; //XMLHttpRequest객체 생성을 위한 크로스 브라우징 if (window.ActiveXObject){ //explorer5.0 이후버전이면 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { //나머지 브라우저 xmlHttp = new XMLHttpRequest(); } return xmlHttp; } function process(xmlHttp) { document.getElementById("rcvPage").innerHTML = xmlHttp.responseText; /* 받아온 데이터문자열(xmlHttp.responseText)을 꺼내서 현재문서(doument)안에 있는 레이어(rcvPage라고 만들어놓은) 안에 HTML로 바꿔줘라.. */ } </script> </head> <body> 전송버튼을 클릭하면 화면 리플래쉬없이 서버측의 데이터를 얻어올 수 있습니다. <input type="button" value="전송" onClick="javascript:load('msg.txt');" / > <input type="button" value="전송" onClick="javascript:load('msg.jsp');" / > <div id="rcvPage"></div> </body> </html>