AJAX

AJAX (4) 서버로 데이터 전송 후 조회된 객체를 응답데이터로 받기

동동이임 2023. 7. 8. 17:40

■ 서버로 데이터 전송 후 조회된 객체를 응답데이터로 받기

● jsp에서 html코드 작성하기

회원 아이디 : <input type="text" id="userId">
회원 비밀번호 : <input type="password" id="userPwd">
<button onclick="test3();">조회</button>
	
<div id="output3"></div>

html 페이지

● script 코드 작성하기

<script>
	function test3() {
		$.ajax({
			url : "jqAjax3.do",
			data : {
				userId : $("#userId").val(),
				userPwd : $("#userPwd").val()
			},
			success : function(result){
				let resultStr = "회원번호 : " + result.userNo + "<br>" +
								"이름 : " + result.userName + "<br>" + 
								"이메일 : " + result.email + "<br>";
				$("#output3").html(resultStr);
			},
			error : function(req, status, error) {
				console.log(req, status, error);
			}
		});
	};
</script>

 

● jqAjax3.do servlet 코드 생성

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	String userId = request.getParameter("userId");
	String userPwd = request.getParameter("userPwd");
		
	Member m = new MemberService().loginMember(userId, userPwd);

	response.setContentType("application/json; charset=UTF-8");

	// GSON : Google JSON
	// GSON 라이브러리 연동
		
	new Gson().toJson(m, response.getWriter());
	// toJson(응답할 객체, 응답할 스트림) : 응답할 스트림으로 응답할 객체를 자동으로 JSON형태로 변환하여 전달시킨다.
	// 응답할 객체가 일반 VO객체라면 JSONObject로 만들어져서 응답
	// 응답할 객체가 ArrayList라면 JSONArray로 만들어져서 응답
		
}

 

● 결과 확인

ajax 테스트 결과