등록 버튼에 기능이 없으므로 API를 호출하는 JS를 만들기 위해 resources에 static/js/app 디렉토리를 생성후 index.js 생성
브라우저의 스코프는 공용 공간으로 쓰이므로 중복된 함수 이름이 발생하여 먼저 로딩된 js의 function에 덮어쓰는 문제 발생
var index란 객체를 만들어 해당 객체에서 필요한 모든 function을 선언해 index 객체 안에서만 function이 유효하도록 해결
예) var main = {...} 코드를 선언하여 index라는 변수의 속성으로 function을 추가하여 index.js만의 유효 범위를 만들어 사용
// index.js
var main = {
init : function () {
var _this = this;
$('#btn-save').on('click', function () {
_this.save();
});
},
save : function () {
var data = {
title: $('#title').val(),
author: $('#author').val(),
content: $('#content').val()
};
$.ajax({
type: 'POST',
url: '/api/v1/posts',
dataType: 'json',
contentType:'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function() {
alert('글이 등록되었습니다.');
window.location.href = '/'; // 글 등록이 성공하면 메인페이지(/)로 이동
}).fail(function (error) {
alert(JSON.stringify(error));
});
}
};
main.init();
생성된 index.js를 머스테치 파일이 쓸 수 있게 footer.mustache에 추가
스프링부트는 src/main/resources/static에 위치한 자바스크립트, CSS, 이미지 등 정적 파일들을 URL에서 /로 설정
// footer.mustache
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- index.js 추가 : 절대 경로(/)로 바로 시작 -->
<!-- 스프링부트는 src/main/resources/static에 위치한 자바스크립트, CSS, 이미지 등 정적 파일들을 URL에서 /로 설정 -->
<script src="/js/app/index.js"></script>
</body>
</html>