본문 바로가기
JS & TS/Frontend

[JSP] Ajax (jquery)

by heekng 2021. 3. 20.
반응형

[JSP] Ajax (jquery)

이전 포스팅에서 Javascript에서 Ajax를 이용하는 방법에 대하여 알아보았다.

2021.03.11 - [JSP/JSP정리] - [JSP] Ajax

 

[JSP] Ajax

[JSP] Ajax 이전까지 배운 데이터 전송방식은 페이지 전체가 이동하며 데이터를 가공한 후 이용했다. 하지만 회원가입페이지의 경우 중복확인 버튼과 같은 현재 페이지 내에서 정보를 가공한 후

heekng.tistory.com

 

 이번에는 jQuery에서 Ajax를 이용하는 방법에 대해 알아보자.


Javaxcript와 jQuery에서 Ajax를 이용하는 방법의 차이

기본적인 Ajax의 구조는 Javascrip를 이용하는 문법과 jQuery문법의 차이밖에 없다.

하지만 jQuery를 사용하는 이점은 코드가 간결화된다는 장점이 있다.

Javascript를 이용할 때

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Javascript로 Ajax 요청보내기</title>
</head>
<body>
	<h1>POST방식의 요청</h1>
	<button type="button" onclick="sendRequest()">POST방식으로 요청 보내기!</button>
	<p id="text"></p>
</body>
<script>
	function sendRequest(){
		var httpRequest = new XMLHttpRequest();
		//POST방식의 Ajax통신
		httpRequest.open("POST", "request_ajax.jsp", true);
		httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		httpRequest.send("city=Seoul&zipcode=55775");
		
		httpRequest.onreadystatechange = function(){
			if(httpRequest.readyState == XMLHttpRequest.DONE && httpRequest.status == 200){
				document.getElementById("text").innerHTML = httpRequest.responseText;
			}
		}
	}
</script>
</html>

jQuery를 이용할 때

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery로 Ajax 요청보내기</title>
</head>
<body>
	<h1>POST방식의 요청</h1>
	<button type="button" onclick="sendRequest()">POST방식으로 요청 보내기!</button>
	<p id="text"></p>
</body>
<script src="//code.jquery.com/jquery-3.5.1.min.js" ></script>
<script>
	function sendRequest(){
		$.ajax({
			url : "request_ajax.jsp",
			type : "post",
			data : {"city" : "Seoul", "zipcode" : "12345"},
			dataType : "text",
			success : function(result){
				document.getElementById("text").innerHTML = result;
			}
		});
	}
</script>
</html>

위처럼 직접 작성해야 하는 소스코드의 복잡성이 줄어들고, 일관되게 코드를 작성할 수 있다.

반응형

'JS & TS > Frontend' 카테고리의 다른 글

[JSP] EL문과 JSTL  (0) 2021.03.23
[JSP] JSON  (0) 2021.03.14
[JSP] Ajax  (0) 2021.03.11
[JSP] 내장 객체, 데이터 전송방식  (0) 2021.02.27
[JSP] 자바빈즈(자바 객체)  (0) 2021.02.27
[JSP] JSP문서 작성 및 코드 작성  (0) 2021.02.27