본문 바로가기
Java Web Programming/5. JavaScript | Ajax | jQuery (JSON)

[Ajax/jQuery] jQuery 를 활용한 Ajax 방식 프로그래밍

by 파프리카_ 2020. 10. 8.
728x90
반응형

[ 목차 ] : 클릭하여 목차 이동

0. 이론
1. JSONObject와 JSONArray
2. jquery ajax(get방식으로 Servlet을 거쳐서 데이터를 받아옴) 
3.  jquery ajax(post방식으로 Servlet을 거쳐서 데이터를 받아옴) 
4. jquery ajax(JSON 객체 활용)
5. serialize()

 


ajax [asynchronous javascript and xml]
비동기 방식 통신 
기존 동기적 방식과 비교하면 전체 페이지를 로딩하는 것이 아니라 
필요한 부분 데이터만 전달받아 화면에 표현 (서버의 부담이 줄어든다)
사용자의 편의성 증대 (요청 후 다른 작업이 가능하고 페이지가 변경되지 않으므로 로컬에서 작업하는 것으로 느낀다)

xml or json의 필요성 : 구조화된 데이터를 처리 

ajax 개발 패턴 
1. XmlHttpRequest 생성 
2. callback 함수 등록 
3. open(method,url);
4. send(data)
5. callback함수 정의 

ajax 개발시 위와 같은 개발패턴이 반복된다. 
-> jQuery에서는 간단한 메서드 호출만으로 위와 같은 ajax 처리가 가능하다. 

jQuery Ajax
- json 이 아닌 일반 데이터(텍스트)로 응답받을 때 형식

$.ajax({ 
	type:"", 
	url:"", 
	data:"", 
	success:function(data){ 

	} 
});

 

- json으로 응답받을 때 형식

$.ajax({ 
	type:"", 
	dataType:"json", 
	url:"", 
	data:"", 
	success:function(data){ 

	} 
}); 





1. JSONObject와 JSONArray

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<title>JSONObject와 JSONArrayTest</title>
<script type="text/javascript">
	function testObj(){
		//alert("jsonobject test");
		var per={name:"아이유", age:28};// 자바스크립트 객체 (JSON: Javascript Object Notation)
		alert(per.name+ " " + per.age);
	}
	function testArray(){
		var pa=["ioc", "aop", "springmvc"]; //자바스크립트 배열 객체 ( JSON Array )
		for (var i = 0; i < pa.length; i++) {
			alert(pa[i]);
		}
	}
	//자바스크립트 생성자
	function Person(name, age){
		this.name=name;
		this.age=age;
	}
	function testPerson(){
		//자바스크립트 생성자를 이용해 객체 생성
		var p=new Person("조승우", 39);
		alert(p.name);
		alert(p.age);
	}
	
</script>
</head>
<body>
<div class="container">
<input type="button" value="JSONObject Test" onclick="testObj()">
<input type="button" value="testArray Test" onclick="testArray()">
<input type="button" value="JavascriptObject" onclick="testPerson()">
</div>
</body>
</html>

1. JSONObject 버튼 눌렀을 때

2. testArray 버튼 눌렀을 때

3. Javascript 버튼 눌렀을 때

 


2. jquery ajax(get방식으로 Servlet을 거쳐서 데이터를 받아옴)

<%-- step1.html --%>
<!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>
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#ajaxBtn").click(function(){
			//alert($(this).val());
			$.ajax({
				type:"get", 
				url:"CountServlet",
				data:"userId=javaking",
				success:function(result){//result변수로 응답정보가 전달됨
					alert(result);
				}
			});//ajax
		});//click
	});//ready
</script>
</head>
<body>
<input type="button" id="ajaxBtn" value="ajax연동테스트">
<span id="resultView"></span>
</body>
</html>
/*     CountServlet.java		*/
package step1;

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;

/**
 * Servlet implementation class CountServlet
 */
@WebServlet("/CountServlet")
public class CountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    int count;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		//Ajax 통신의 응답방식은 
		//웹페이지로 응답하는 것이 아니라 
		//필요한 데이터만 응답한다 
		String id=request.getParameter("userId");				
		out.print(id+" "+count++);
		out.close();
	}
}

 

버튼눌렀을경우


3.  jquery ajax(post방식으로 Servlet을 거쳐서 데이터를 받아옴)

<%-- step2.html	--%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
			$("#ajaxBtn").click(function(){
				//alert($(this).val());
				$.ajax({
					type:"post", 
					url:"CommentServlet",
					data:"comment="+ $("#comment").val() ,
					success:function(result){//result변수로 응답정보가 전달됨
						//아래 div id resultView에 정보를 보여준다
						//$("#resultView").text(result);
						$("#resultView").html("<pre>" + result + "</pre>");
					}
				});//ajax
			});//click
	});//ready
</script>
</head>
<body>
	<textarea rows="10" cols="10" id="comment"></textarea>
	<br>
	<input type="button" id="ajaxBtn" value="ajax연동테스트">
	<hr>
	<div id="resultView"></div>
</body>
</html>
/*	CommentServlet	*/

package step2;

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;

/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/CommentServlet")
public class CommentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		String comment=request.getParameter("comment");				
		out.print(comment+" \n서버에 갔다가 왔어용^_^");
		out.close();
	}

}

ajax연동테스트 버튼을 눌렀을 경우

(pre태그가 적용되어 줄바꿈이 적용되었다!)


4. jquery ajax(JSON 객체 활용)

<%-- step3-json.html --%>
<!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>
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#jsonObjBtn").click(function(){
			$.ajax({
				type:"get",
				url:"JSONServlet",
				dataType:"json",	//xml을 쓸 경우 xml이라고 명시
				data:"command=getMemberInfo",
				success:function(jsonData){
					//alert(jsonData.name+ " " + jsonData.age);
					$("#nameView").text(jsonData.name);
					$("#ageView").text(jsonData.age);
				}
			});//ajax
		});//click
		
		$("#jsonArrayBtn").click(function(){
			$.ajax({
				type:"get",
				url:"JSONServlet",
				dataType:"json",	//xml을 쓸 경우 xml이라고 명시
				data:"command=getMemberList",
				success:function(ja){
					//alert(jsonData.length);
					for (var i = 0; i < ja.length; i++) {
						alert(ja[i]);
					}//for
				}//success
			});//ajax
		});//click
	});//ready
</script>
</head>
<body>
<input type="button" id="jsonObjBtn" value="JSONObject테스트">
<hr>
이름 : <span id="nameView"></span><br>
나이 : <span id="ageView"></span>
<hr>
<!-- 아래 버튼 누르면 ajax 통신을 통해 아이유 갈비 갈매기가 
	  각각 alert으로 출력 
 -->
<input type="button" id="jsonArrayBtn" value="JSONArray테스트">
<hr>
</body>
</html>
/*	JSONServlet	*/
package step3;

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;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Servlet implementation class JSONServlet
 */
@WebServlet("/JSONServlet")
public class JSONServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	int age;
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();		
		//JSON 
		String command=request.getParameter("command");
		if(command.contentEquals("getMemberInfo")) {
			 JSONObject json = new JSONObject();
	         json.put("name", "아이유");
	         json.put("age", age++);
	         out.print(json.toString());
		}else if(command.contentEquals("getMemberList")) {
			JSONArray ja=new  JSONArray();
			ja.put("배두나");
			ja.put("조승우");
			ja.put("서검사");
			out.print(ja.toString());
		}
		out.close();
	}	
}

1. JSONObject테스트 버튼을 눌렀을 경우(count++이라서 누를 때 마다 나이가 올라간다.)

2. JSONArray테스트 버튼을 눌렀을 경우

 


5. serialize() - ajax에서 자동으로 query string을 만들어주는 메서드

<!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>jquery serialize</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#test").click(function(){
			//f1 아이디 폼의 name과 value 정보를 query string 으로 생성해 준다 
			alert($("#f1").serialize());
		});	
	});
</script>
</head>
<body>
<!-- ajax 방식으로 서버 전송시
	 data: "name=장기하&age=18&hobby=겜&hobby=노래" 와 같은 
	 query string 을 만들어 전송해야 한다 
  -->
 <form id="f1" action="front">
  이름 :<input type="text" name="name">
   <input type="hidden"
   name="command" value="register"> 
   <select name="tool">
   <option value="notepad">메모장</option>
   <option value="editplus">에디트플러스</option>
   <option value="eclipse">이클립스</option>
  </select> 
  <br>
  <input type="checkbox" name="menu" value="beer">맥주<br>
   <input type="checkbox" name="menu" value="pizza">피자<br> 
   <input type="button" value="test" id="test">
 </form>
</body>
</html>

실행결과

 

728x90
반응형