본문 바로가기

카테고리 없음

공공 api 가져다가 쓰는법

1. career.go.kr에서 인증키 받아야함. 학교정보 open API

https://www.career.go.kr/cnet/front/openapi/openApiSchoolCenter.do

 

2.json형태를  우리는 쓸거임

 

<th:block layout:fragment="customJs">
	<!-- 자바스크립트 작성 공간 -->
<script>

//요청 변수 객체를 미리 만드는거
		const paramObj = {
			'apiKey': '859cebe396f10dc67ea051a696e832e3',
			'svcType': 'api',
			'svcCode': 'SCHOOL',
			'contentType': 'json',
			'gubun': 'univ_list',
			'perPage' : 1000 // 이거를 써야 페이지 전체가 보
		};

		$('#searchButton').click(function (e) {
			let inputBox = $('#inputBox').val().replaceAll(' ',''); //.val=데이터값을 취득
			
			// 값이 비어있을 때
			if(inputBox == ''){
				let univUl = $('#univUl');
				univUl.empty();
				univUl.append("<li>검색결과가 없습니다.</li>");
				return;
			}
			
			$.ajax({
				url: "https://www.career.go.kr/cnet/openapi/getOpenApi",
				method: "get",
				dataType: "json",
				data: paramObj,//어떤 데이터를 가지고 uri를 통해서 가지고 오고  싶은지 미리 정의 하는거임 
				success: function (data) {
					//console.log(data);
					// Ul 태그 초기화 
					let univUl = $('#univUl')
					univUl.empty();
					let univList = data.dataSearch.content;
					univList = univList.filter(item=>{
						console.log(item);
						let targetValue = item.schoolName;
						targetValue = targetValue.replaceAll(' ', '');
						return (targetValue.indexOf(inputBox) > -1 );
					})
					// 검색한 값이  없을 때  
					if(univList.length == 0){
						univUl.append("<li>검색결과가 없습니다.</li>");
						return;
					}

					// 대학교 정보 반복문으로 이름 가져오기 
					
					for (let i = 0; i < univList.length; i++) {
						let univName = univList[i].schoolName;
						console.log(univName);
						univUl.append("<li><a href='#' class='selectUniv' data-univ-name=" + univName + "><h6>" + univName + "</h6></a></li>")
					}
					
					

				},
				error: function (error) {
					console.log(error);
				}
			})
		});
	</script>
</th:block>