🌎 Web

[Web] Day37 - ajax() / JSON

harveydent 2023. 6. 27. 23:12
728x90

Ajax

Ajax란 Asynchronous JavaScript and XML을 의미합니다. Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있게 해줍니다. 또한, 백그라운드 영역에서 서버와 데이터를 교환하여 웹 페이지에 표시해 줍니다.

jQuery에서는 Ajax 기능을 손쉽게 사용할 수 있도록 여러 메서드를 제공하고 있습니다. 이러한 메서드를 사용하면 HTTP 요청(request)을 손쉽게 보낼 수 있습니다. 또한, 데이터의 종류에 따라 그에 알맞는 메서드를 사용하여 서버에 데이터를 요청할 수 있습니다.

$.ajax() 메서드

ajax() 메서드는 모든 제이쿼리 Ajax 메서드의 핵심이 되는 메서드입니다. HTTP 요청을 만드는 방법을 제공합니다.

JSON

JSON은 JavaScript Object Notation의 약자입니다. JSON은 좀 더 쉽게 데이터를 교환하고 저장하기 위하여 만들어진 텍스트 기반의 데이터 교환 표준입니다.

[
	{"name":"홍길동", "score1":50, "score2":100},
	{"name":"아무개", "score1":75, "score2":82}
]

실습

실습 1

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax() 메서드와 JSON 데이터</title>
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
<script type="text/javascript">
	// 페이지 이동없이(별도의 페이지 호출없이),
	// 현재 페이지에서 필요한 데이터를 바로 로드해서 작업가능한,
	// "비동기 처리"를 지원하는 ajax() 메서드
	$.ajax({
		// GET : R
		// POST : C U D
		type: "GET",
		url: "json/data01.json",
		dataType: "json",
		success: function(data) {
			//console.log(data);
			
			var elem = "";
			// JSON 데이터가 키-값 쌍으로 구성이 되어있는 데이터이기 때문에 each() 메서드 활용가능
			$.each(data, function(index, obj){
				elem += "<tr>";
				//console.log(obj.name);
				elem += "<td>" + obj.name + "</td>";
				//console.log(obj.score1);
				elem += "<td>" + obj.score1 + "</td>";
				//console.log(obj.score2);
				elem += "<td>" + obj.score2 + "</td>";
				elem += "</tr>";
			}); 
			$('tbody').append(elem);
		},
		error: function(err) {
			console.log('에러발생!');
			console.log(err.errorText);
		}
	});
</script>
</head>
<body>
	<table border="1">
		<thead>
		<tr>
			<th>학생이름</th>
			<th>중간고사</th>
			<th>기말고사</th>
		</tr>
		</thead>
		<tbody>			
		<!-- JSON으로부터 데이터를 받아와서 화면에 출력할 예정 -->
		</tbody>
	</table>

</body>
</html>

 

실습 2

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습1</title>
<script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
<script type="text/javascript">
	$.ajax({
		type: "GET",
		url: "json/data02.json",
		dataType: "json",
		success: function(data) {
			var elem = '';
			$.each(data, function(index, obj) {
				elem += '<a href="' + obj.link + '">';
				elem += '<img alt="' + obj.fileName + '" src="images/' + obj.filePath + '">';
				elem += '</a>'
			});
			$('#wrap').append(elem);
		},
		error: function(err) {
			console.log('에러발생!');
			console.log(err.errorText);
		}
	});
</script>
</head>
<body>
	<div id="wrap">
	</div>
</body>
</html>

GitHub

https://github.com/Qkrwnsgus0522/Web

 

GitHub - Qkrwnsgus0522/Web

Contribute to Qkrwnsgus0522/Web development by creating an account on GitHub.

github.com

 

728x90