자바40일차

달달한스위츠·2024년 4월 9일

자바배우기

목록 보기
37/43

오늘의 코드

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<title>jQuery Ajax load</title>
</head>
<body>
	<div id="output">
		<h2>jQuery Ajax로 현재 텍스트 변경</h2>
	</div>
	<button>외부 컨텐츠 가져오기</button>
	<script type="text/javascript">
		// * jQuery Ajax	
		// * jQuery는 Ajax의 다양한 기능을 사용할 수 있음	
		// * jQuery Ajax 메소드를 사용하면
		// * 서버에서 텍스트, HTML, XML 또는 JSON 요청이 가능
		// * $(selector).load(URL, data, callback);
		
		// URL : 파일 또는 서버 통신 경로
		// data : 보낸 데이터
		// callback : load가 수행되고 해야할 기능
	
		$(document).ready(function(){
			$('button').click(function(){
				$('#output').load("01_demo_test.txt #p1");
				// 01_demo_test.txt의 id=p1 내용을 #output에 저장한다.
			});
		});
		
		
	</script>
	
	
</body>
</html>

txt

<h2>안녕?</h2>
<p id="p1">봄날씨입니다~</p>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<title>jQuery Ajax load</title>
</head>
<body>
	<div id="output">
		<h2>jQuery Ajax로 현재 텍스트 변경</h2>
	</div>
	<button>외부 컨텐츠 가져오기</button>
	<script type="text/javascript">
		// * $(selector).load(URL, data, callback);
		
		// 시점에 따라 다르단 것을 잘 알고 있어야 한다.
		$(document).ready(function(){
			$('button').click(function(){
				$('#output').load("01_demo_test.txt #p1", function(responseTxt, statusTxt, xhr){
					if(statusTxt == "success") { // 데이터 송수신이 성공하면
						alert('외부 컨텐츠 로드 성공');
					} else {
						alert('Error : ' + xhr.status + " : " + xhr.statusText);
					}
				});
				// 01_demo_test.txt의 id=p1 내용을 #output에 저장한다.
			});
		});
		
		
	</script>
	
	
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<title>Ajax Method</title>
</head>
<body>
	<div id="output">변경될 텍스트</div>
	<button>외부 컨텐츠 가져오기</button>
	<script type="text/javascript">
		// * $.ajax()
		// - ajax load 메소드를 간략화한 메소드
		// - 기본 형태
		//   $.ajax({name : value, name : value, ...});
		// - name으로 선택할 수 있는 요소
		//   type : GET or POST
		//   url : 경로
		//   data : 보낼 데이터 패키지
		//   success : 호출 성공 시 리턴될 내용
		
		$(document).ready(function(){
			$('button').click(function(){
				$.ajax({
					type : "get",
					url : "../ajax_test.do",
					data : {
						id : "test", // request parameter
						pw : "1234"
					},
					success : function(result) {
						// result : ajax_test.do에서 작성된 내용을 리턴해서 저장한 결과
						console.log(result);
						$('#output').html(result);
					}
				}); // end ajax()
			}) // end button.click()
		}); // end document
		
		
	</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<title>Get Method</title>
</head>
<body>
	<button>HTTP Get Request를 JSP에 보내고, 그 결과를 가져오는 버튼</button>
	<script type="text/javascript">
	// $.get(url, callback);
	$(document).ready(function(){
		$('button').click(function(){
			$.get('04_get_test.jsp', function(data, status){
				alert("Data : " + data + "\n status : " + status);
				
			}); // end get()
		}); // end button.click()
	}); // end document()
	
	</script>
	
	
</body>
</html>

test

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%out.write("Ajax Get 테스트"); %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<title>Post Method</title>
</head>
<body>
	<button>HTTP Post Request를 JSP에 보내고, 그 결과를 가져오는 버튼</button>
	<script type="text/javascript">
		// $.post(url, data, callback);
		$(document).ready(function(){
			$('button').click(function(){
				$.post("05_post_test.jsp",
						{
							name : "mok",
							city : "인천"
						},
						function(data, status){
							alert("Data : " + data + "\n status : " + status);
						}); // end post()
			}); // end button.click()
			
		}); // end document
		
	</script>
	
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String name = request.getParameter("name");
	String city = request.getParameter("city");
	
	out.write("name : " + name + ", city : " + city);

%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.7.1.js">
</script>
<title>Ajax JSON</title>
</head>
<body>
	<p id="output"></p>
	<script type="text/javascript">
	$(document).ready(function(){
		$.ajax({
			type : "get",
			url : "06_json_test.txt",
			success : function(result) {
				console.log(result);
				console.log(typeof(result));
				// 즉석 퀴즈. 전송받은 json 데이터를 id="output"인 태그에 보여주기
				// 예시)
				// 이름 : mok
				// 나이 : 20
				// 팻 : dog, 이름 : choco
				// 팻 : cat, 이름 : navi
				
				let obj = JSON.parse(result);
				
                let output = "";
                
                output += "이름 : " + obj.name + "<br>";
                output += "나이 : " + obj.age + "<br>";
                	for(let i in obj.pets) {
               		 output += "팻 : " + obj.pets[i].animal + ", 이름 : " + obj.pets[i].name + "<br>";
                	}
                
                $("#output").html(output);
                
			}
		}); // end ajax()
	}); // end document
	</script>
	
</body>
</html>
{
	"name" : "mok",
	"age" : 20,
	"pets" : [
		{"animal" : "dog", "name" : "choco"},
		{"animal" : "cat", "name" : "navi"}
	]
}

0개의 댓글