Web/Javascript

[Javascript] AJAX 와 JSON

웹코린이 2023. 6. 29. 15:23
728x90

 

 

AJAX

웹 페이지를 새로 고치지 않고도 비동기적으로 서버와 데이터를 교환하고 업데이트하는 데 사용됨

 

 

JSON

데이터를 교환하기 위한 경량 데이터 형식
텍스트 형식으로 구조화된 데이터를 나타내며, 주로 서버와 클라이언트 간의 데이터 교환 형식으로 사용됨

 

 

실습

 

JSON 데이터

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

 

 

 

실습 1 : ajax() 와 JSON 데이터를 불러와 테이블로 출력

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax() 메서드와 JSON 데이터</title>


</head>
<body>

<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: "data01.json",
		dataType: "json",
		success: function(data){
			console.log(data);
			
			var elem = "";
			// JSON 데이터가 키-값 쌍으로 구성이 되어 있는 데이터이기 때문에 each() 메서드 활용가능
			$.each(data, function(index, obj){
				elem+="<tr>";
				elem+=("<td>"+obj.name+"</td>");
				elem+=("<td>"+obj.score1+"</td>");
				elem+=("<td>"+obj.score2+"</td>");
				elem+="</tr>";
				$('tbody').append(elem);
				
				console.log(obj.name);
				console.log(obj.score1);
				console.log(obj.score2);
			});
		},
		error: function(err){
			console.log('에러발생!');
			console.log(err.errorText);
		}
		
	});
</script>

<table border = "1">
	<thead>
	<tr>
		<th>학생이름</th><th>중간고사</th><th>기말고사</th>
	</tr>
	</thead>
	
	<tbody>
		<!-- JSON으로부터 데이터를 받아와서 화면에 출력할 예정 -->
	</tbody>
</table>

</body>
</html>

 

 

실습 2 : ajax() 와 JSON 데이터를 불러와 테이블로 출력 2

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>실습01</title>
</head>
<body>
	<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 : "data02.json",
			dataType : "json",
			success : function(data) {

				console.log(data);

				// JSON 데이터가 키-값 쌍으로 구성이 되어 있는 데이터이기 때문에 each() 메서드 활용가능
				$.each(data, function(index, obj) {
					var elem = "";

					elem += ("<a href='"+obj.link+"'>");
					elem += ("<img alt='" + obj.fileName + "'");
					elem += (" src='images/" + obj.filePath + "' /></a>");

					$('div').append(elem);
				});

			},

			error : function(err) {
				console.log('에러발생!');
				console.log(err.errorText);
			}

		});
	</script>

	<div></div>

</body>
</html>

 

728x90