학원/수업 기록

[AJAX/jQuery] 공공데이터 JSON 파일을 웹 브라우저로 보이기 (시험)

60cod 2022. 9. 21. 10:46

데이터 구조

JSON 객체의 "DATA" 키로 된 배열(값)의 JSON 객체들의 키

  • inf_id : 서비스 ID
  • inf_nm : 서비스명
  • api_service_nm : 서비스명 (영문)
  • exm_nm : 기본샘플명
  • exm_url : 기본샘플주소



AJController

package com.spring.sample.web.testa.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class AJController {
	  @RequestMapping(value ="Json")
      public ModelAndView Json(ModelAndView mav) {
		  mav.setViewName("testa/J/Json");
  
          return mav;
      }

}

주소 만들어주고 jsp 파일 위치 연결해줌.


testa/J/Json.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
	border-collapse : collapse;
}

td, th {
	border : 1px solid #000;
	height : 30px;
	text-align : center;
}
</style>
<!-- JQuery -->
<script type="text/javascript"
      src="resources/script/jquery/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$.ajax({
		url: "resources/json/Seoul_OpenAPI_state.json",
		type: "GET",
		dataType: "json", 
		success: function(res) { 
			var html = ""; 
		 	
			for(var i=0; i<res.DATA.length; i++){
				html += "<tr>";
				html += "	<td>" + res.DATA[i].inf_id + "</td>";
				html += "	<td>" + res.DATA[i].inf_nm + "</td>";
				html += "	<td>" + res.DATA[i].api_service_nm + "</td>";
				html += "	<td>" + res.DATA[i].exm_nm + "</td>";
				html += "	<td>" + res.DATA[i].exm_url + "</td>";
				html += "</tr>";
			}
			 
		$("tbody").html(html);
		},
		error : function(request, status, error) { 
			console.log(request.responseText); 
		}
	});
	
});
</script>
</head>
<body>
<table>
	<thead>
		<tr>
			<th>서비스 ID</th>
			<th>서비스명(한글)</th>
			<th>서비스명(영문)</th>
			<th>기본샘플명</th>
			<th>기본샘플주소</th>
		</tr>
	</thead>
	<tbody></tbody>
</table>
</body>
</html>

resources 안에 JSON 파일을 넣어 위치 경로 지정해주었고
DATA.length로 반복문 돌리고 인덱스로 꺼내서 tbody를 그렸다.