waitedForU
[08] XMLHttpRequest Module, XMLHttpRequest Module 실습 본문
1. XMLHttpRequest 모듈
- Parameter상에 한글이 들어가면 손상됨으로 문자열을 "UTF-8"로 인코딩해주는 encodeURIComponent()함수를 사용 합니다.
>>>>> WebContent/basic/httpRequest.js
//XMLHttpRequest 객체
var httpRequest = null;
// url: 요청 주소
// params: 서버로 보내는 값의 목록
// response_function_name: 응답 결과를 처리할 함수
// method: GET, POST인지 결정
function sendRequest(url, params, response_function_name, method) {
if (window.XMLHttpRequest) {
// code for modern browsers
httpRequest = new XMLHttpRequest();
} else {
// code for IE6, IE5
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
// document.write("httpRequest:"+httpRequest);
// 소문자로 변경
httpMethod = method.toLowerCase();
// 전송 값이 있는지 검사
var httpParams = (params == null || params == '') ? null : params;
var httpUrl = url;
// GET방식이면 GET 방식으로 조합
if (httpMethod == 'get' && httpParams != null) {
httpUrl = httpUrl + "?" + httpParams;
}
// 서버로 연결
httpRequest.open(httpMethod, httpUrl, true);
// 내용 타입 지정
httpRequest.setRequestHeader(
'Content-Type', 'application/x-www-form-urlencoded');
// 응답을 처리할 함수 지정
httpRequest.onreadystatechange = response_function_name;
// 전송 방식이 POST이면 파라미터 전송
// GET 방식이면 null 지정
httpRequest.send(httpMethod == 'post' ? httpParams : null);
}
// 실행 결과를 출력, Debugging
function log(msg) {
var console = document.getElementById("debugConsole");//div tag
if (console != null) {
console.innerHTML += msg +"<br/>";
}
}
// 태그를 보여줌
function show(elementId) {
var element = document.getElementById(elementId);
if (element) {
element.style.display = '';
}
}
// 태그를 숨김
function hide(elementId) {
var element = document.getElementById(elementId);
if (element) {
element.style.display = 'none';
}
}
2. XMLHttpRequest 모듈 실습
1) JSP Server Page
- 요청 페이지 입니다.
>>>>> WebContent/basic/pay.jsp
- Test: http://localhost:8000/ajax_test/basic/pay.jsp?id=test&passwd=1234
<%@ page contentType = "text/plain; charset=UTF-8" %>
<%
String[] titles = {
" 급 여 명 세 서 ",
"기 본 급: 1,500,000 원",
"야근수당: 100,000 원",
"주말수당: 200,000 원",
"세금합계: 100,000 원",
"실수령액: 1,700,000 원",
"입금 예정일: 2008-01-01일 수고하셨습니다.",
};
%>
<ul>
<font color='green'><u>
<%
String id = request.getParameter("id");
String passwd = request.getParameter("passwd");
if (id.equals("test") && passwd.equals("1234")){
for (int i = 0 ; i < titles.length ; i++) {
out.println("<li>" + titles[i] + "<br/><br/>");
}
}else{
out.println("<li>인증 실패입니다.<br/><br/>");
out.println("<li>다시 시도해 주세요.<br/><br/>");
}
%>
</u></font>
</ul>
2). HTML(ajax사용페이지)
>>>>> WebContent/basic/pay.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>PAY</title>
<script type="text/javascript" src="./httpRequest.js"></script>
<script type="text/javascript">
// 서버로 요청 전송
function send(id, passwd) {
log("send() 함수 호출"); // 처리 단계 기록
log("ID: " + id + " PASSWD: " + passwd);
var params = "id="+encodeURIComponent(id);
log("params: " + params);
params = params + "&passwd="+encodeURIComponent(passwd);
// 태그중에 "payList"을 찾아 옵니다.
var newsList = document.getElementById("payList");
newsList.innerHTML=""; // 태그의 내용 삭제
// sendRequest()
// 인수1: 서버로 요청하는 파일명, jsp, servlet
// 인수2: 파라미터 목록
// 인수3: 응답 처리 메소드, 함수 이름
// 인수4: 전송방식(post, get)
// response = response(){ }
sendRequest("pay.jsp", params, response, "post");
}
function response() {
if (httpRequest.readyState == 4) { // 전송을 전부 받았다면
if (httpRequest.status == 200) { // 요청한 서버 파일이 실행 됐다면
// 태그중에 "newsList"을 찾아 옵니다.
var payList = document.getElementById("payList");
// 서버로부터 전송된 문자열
// div 태그의 값으로 responseText값을 할당합니다.
payList.innerHTML = httpRequest.responseText;
}
}
}
// 문서가 브러우저로 로딩되면 자동으로 호출되는 메소드
// window.onload = function() {
// send();
// }
</script>
<style type="text/css">
<!--
.style9 {font-size: 16}
-->
</style>
</head>
<body>
<!-- 디버깅 정보를 출력하는 DIV 태그 -->
<div id="debugConsole"
style="border: 1px solid #000000; color:#00ff00; background:#000000 ">
</div>
<table width="790" border="1" align="center" cellpadding="5">
<tr>
<td height="34" align="center">
<span class="style9"> 급여 명세서 </span></td>
</tr>
<tr>
<td height="61">
<!-- 결과 출력 태그 -->
<div id="payList"></div>
<br>
<form name="news">
급여확인 로그인: <br><br>
사원 ID:
<input type="text" name="id" value="test">
패스워드:
<input type="password" name="passwd" value="1234">
<input type="button" name="cmdRefresh"
value="급여 확인" onclick="send(this.form.id.value, this.form.passwd.value)" />
</form>
</td>
</tr>
</table>
</body>
</html>
'Ajax' 카테고리의 다른 글
[10] [제시어] JDBC 설정, DB 설정, Servlet (0) | 2016.05.19 |
---|---|
[07] Ajax-Request,Response, Ajax-The onreadystatechange Event (0) | 2016.05.18 |
[06] XMLHttpRequest Object , XMLHttpRequest 생성 (0) | 2016.05.18 |
[05] Ajax(Asynchronous JavaScript and XML) (0) | 2016.05.18 |
[02] HTML DOM 실습 1 (0) | 2016.05.17 |
Comments