본문 바로가기
CLASS/AJAX

#2-1 / id 중복체크 연습용(ajax) - POST

by eungSe__ 2024. 6. 24.

Ajax Get : json 파일을 로드하기 위해

but 중복체크는 값을 보내야 하므로 ( Ajax jsp -> do 로 ) => Post 통신 사용

( 보내고 받는게 없으면 .do파일은 error뜨는게 맞음 ! )

⚡ ajax POST 통신 연습용 : 문자열을 return 시켜서 사용함

- jsp
아이디 : <input type="text" name="mid" id="mid">
<input type="button" value="중복확인" id="btn">

 
- jq (js는 하단에 있음)

$(function(){
	$("#btn").click(function(){
		$.ajax({
			url : "./jsp1ok.do",
			cache : false,
			type : "post", //pot 전송(data type,data,contentType 필요)
			//json 배열을 리턴받을 경우 : do 파일이라도 json type으로 받아야함
			  //(걍 문자열만 받으면 html로)
			dataType : "html", 
			data : { //가상의 name을 생성하여 post전송
				mid : $("#mid").val()
			},
			//post 전송 시 문자 또는 파일 형태로 전송가능함
			contentType : "application/x-www-form-urlencoded", 
			success : function($data,$result){
				if($data == "no"){
					alert("이미 사용중인 아이디입니다");
				}else if($data == "error"){
					alert("올바른 값이 아닙니다");
				}else{
					alert("사용 가능한 아이디 입니다");
				}
				console.log($data);
				console.log($result);
			},
			error : function(){
				console.log("통신오류 발생")
			}
			
		});
	});
})


- servlet (.java -> .do)

public class jsp1ok extends HttpServlet {
	private static final long serialVersionUID = 1L;
	PrintWriter pw = null;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/x-json");
		request.setCharacterEncoding("utf-8");

		String mid = request.getParameter("mid");
		String result = "";
		//no : 중복 , yes : 사용가능 , error : 값 전달 오류
		if(mid.equals("hong")) {
			result = "no";
		}else if(mid.equals("")){
			result = "error";
		}else {
			result = "yes";
		}
		
		this.pw = response.getWriter();
		this.pw.print(result); // write : jsp 로드 형태일 때 사용 , print : do만 실행시

		this.pw.close();
	}
}

 

 

 

🔽  이걸 js로 한다면?

<body>
    아이디 : <input type="text" name="mid" id="mid"><br>
    <input type="button" value="js중복확인" onclick="ajax_post()">
</body>
<script>
    function ajax_post(){
        var http, result;
        http = new XMLHttpRequest();
        http.onreadystatechange = function(){
            if(http.readyState==4&&http.status==200){
                result = this.response;
                if(result == "no"){
                    alert("이미 사용중인 아이디입니다");
                }else if($data == "error"){
                    alert("올바른 값이 아닙니다");
                }else{
                    alert("사용 가능한 아이디 입니다");
                }
            }
        }

        http.open("post","./jsp1ok.do",true);
        http.setRequestHeader("content-type","application/x-www-form-urlencoded");
        //get에는 send안에 아무것도 없음
        http.send("mid="+document.getElementById("mid").value);
    }
</script>

 

=> post - js 시 주의

post 통신의 기본 : true,

setRequestHeader 필수

send(가상의 변수 및 값)

배열일 때만 JSON.parse 적용