jQuery

jQuery - 04.Ajax ( 정의, 예제 )

보로로롬 2016. 7. 14. 11:46

Ajax ( Asynchronous JavaScript and Xml )


jQuery 사이트 :  https://api.jquery.com/jquery.get/


비동기 요청으로 페이지가 아닌 데이터만 응답받는 통신 방식

응답받는 데이터의 유형은 Json 혹은 xml


대표적인 기능 : 검색어 추천 / 실시간 검색어 / 아이디 중복확인


활용법


$('select').load(url,[params],[callbackFunc])


jQuery Ajax기능 중 가장 간단한 함수로

첫번째 인수로 지정한 url에 요청을 보내고 결과를 select된 요소에 삽입함

두번째 인자인 params는 요청 파라미터이고

세번째 callbackFunc는 응답수신 완료 후 수행할 메소드

( 두번째랑 세번째는 생략가능 )



서버단에서 동적으로 부여하는것  -> jsp

클라이언트에서 동적으로 부여하는것 -> 자바스트립트



Ajax 예제 ( HTML에서 버튼을 눌러서 요청을 하면 jsp를 가져오는 예제 )

가장 간단한 Ajax예제


-----   whatTime.jsp   ------


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.Date" %>
<!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>
</head>
<body>
현재시간 : <%= new Date() %>
</body>
</html>


-----   load.html   ------


 <!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(function(){
$('#sendAjax').on('click', function(){
$("#result").load('whatTime.jsp');
});
});
</script>
</head>
<body>
<input type="button" id="sendAjax" value="Ajax요청">
<p/>
<div id="result"></div>
</body>
</html>

------------------------------------------------------------------------------- 



Ajax 예제2 ( Servlet에서 버튼을 눌러서 요청을 하면 hello를 가져오는 예제 )

-----   HelloServlet.java   ------
package js1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Hello.do")
public class HelloServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
// super.doGet(req, resp);
System.out.println("Get요청 들어옴");
doProc(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
// super.doPost(req, resp);
System.out.println("Post요청 들어옴");
doProc(req, resp);
}
protected void doProc(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.write("Hello");
writer.flush();
}
}

-----   load.html   ------

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(function(){
$('#sendAjax').on('click', function(){
$('#result').load('Hello.do');
});
});
</script>
</head>
<body>
<input type="button" id="sendAjax" value="Ajax요청">
<p/>
<div id="result"></div>
</body>
</html>



-----   load.html   ------ (팝업으로 뛰우려면 아래처럼)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(function(){
$('#sendAjax').on('click', function(){
// $('#result').load('Hello.do');
$.post('Hello.do',function(data){
alert(data);
});
});
});
</script>
</head>
<body>
<input type="button" id="sendAjax" value="Ajax요청">
<p/>
<div id="result"></div>
</body>
</html>

---- text창에 입력받은 name을 가져오는 예제 -----------------------------------

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<script type="text/javascript">
$(function(){
$('#sendAjax').on('click', function(){
// $('#result').load('Hello.do');
$.post('Hello.do',{
name : $('#name').val()
}, function(data){
alert(data);
});
});
});
</script>
</head>
<body>
<input type="text" id="name">
<!-- name엘리먼트에 작성된 값을 Ajax요청 버튼이 눌렸을때 가지고 Hello.do로 요청을 보내고 -->
<input type="button" id="sendAjax" value="Ajax요청">
<p/>
<div id="result"></div>
<!-- Hello.do는 [name파라미터]님 안녕하세요 라는 값을 응답 -->
</body>
</html>