본문 바로가기

AJAX

AJAX 기본 예제3 POST (회원가입양식에서 바로 검증)

test3.jsp


<%@ page contentType="text/html; charset=UTF-8"%>

<%@page trimDirectiveWhitespaces="true"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

String cp = request.getContextPath();

%>

<!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 type="text/javascript">

//개체 생성

function createXMLHttpRequest() {

var xmlReq = null;


if (window.XMLHttpRequest) { // non IE

xmlReq = new XMLHttpRequest();

} else if (window.ActiveXObject) { //IE

xmlReq = new ActiveXObject("Msxml2.XMLHTTP");

}

return xmlReq;

}


//전역 변수 등장

var xmlHttp;


function idcheck() {

var userId = document.getElementById("userId").value; //클라가 입력한 아이디 대입

if (userId == "") {

document.getElementById("userId").focus();

return;

}

xmlHttp=createXMLHttpRequest(); //xml 개체생성

xmlHttp.onreadystatechange=callback; // 서버작업끝나면 callback 함수  실행

var url = "test3_ok.jsp";

var params = "userId=" + userId;

//POST 방식에서 셋팅해주는 방법

xmlHttp.open("POST", url, true);

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xmlHttp.send(params); //POST방식으로 보낼 데이터를 인자로 넣어준다. 형식) 키=값&키=값

}

function callback() {

if (xmlHttp.readyState == 4) { // 모든 응답 완료

if (xmlHttp.status == 200) { // 상태코드(OK)

printData();

}

}

}


function printData() {

var xmlDoc = xmlHttp.responseXML;

var pass = xmlDoc.getElementsByTagName("pass")[0];

var val = pass.firstChild.nodeValue;

var userId = document.getElementById("userId").value;


var out = document.getElementById("sp");

var result;

if (val == "true") {

result = userId + " 아이디는 사용 가능합니다.";

out.innerHTML = result;

return;

} else {

result = "<font color='red'>" + userId + "아이디는 사용 불가능합니다." + "</font>";

out.innerHTML = result;

document.getElementById("userId").focus();

}

}

</script>

</head>

<body>


<!-- onchange!!!로 ajax 실행 -->

<form action="" method="post">

아이디 : <input type="text" name="userId" id="userId" onchange="idcheck();"><span id="sp"></span><br /> 

패스워드 : <input type="password" name="userPwd"><br /> 

이름 : <input type="text"name="name"><br /> <input type="button" value="회원가입">

</form>


</body>

</html>


==========================================================================================================================================


 test3_ok.jsp


<%@ page  contentType="text/xml; charset=UTF-8"%>

<%@page trimDirectiveWhitespaces="true"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

String cp = request.getContextPath();


String userId=request.getParameter("userId");

String pass="true";

if(userId.equals("test")){

pass="false";

}

%>


<result>

<pass><%=pass%></pass>

</result>