JAVASCRIPT

[js] api를 이용하여 정보 얻어내기 (jquery, json 활용)

개발자 배찌 2022. 2. 5. 22:27
728x90

API 데이터 제공 사이트 >> 공공데이터포털 data.go.kr

 

data.jsp

<%@ page  language="java" contentType="text/html; charset=euc-kr" pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Member List</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="./js/data.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1 style="text-align:center;">JSON Data List</h1>
<table class="table table-striped" id="member_table">
<thead>
<tr>
<th>No</th>
<th>관할 경찰서</th>
<th>다발지역위치</th>
<th>경상자수</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>

</body>
</html>

data.js


$(document).ready(function(){
$.ajax({
//ajax 옵션 설정
url:"http://apis.data.go.kr/B552061/jaywalking/getRestJaywalking?serviceKey=발급받은key",
type:"GET",
dataType:"json",
success:function(data){
    let api_data="";
    $.each(data.items.item, function(key, value){
    api_data += "<tr>";
    api_data += "<td>"+key+"</td>";
    api_data += "<td>"+value.sido_sgg_nm+"</td>";
    api_data += "<td>"+value.spot_nm+"</td>";
    api_data += "<td>"+value.sl_dnv_cnt+"</td>";
    api_data += "</tr>";
});

$('#member_table').append(api_data);
}

});
});