let main = {
init : function () {
let _this = this;
$('#btn-save').on('click', function () {
_this.save();
})
},
save : function () {
let data = {
title: $('#title').val(),
content: $('#content').val(),
author: $('#author').val(),
};
$.ajax({
type: 'POST',
url: '/api/v1/posts',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done(function (){
alert('글이 등록되었습니다.');
location.href = '/';
}).fail(function (error){
alert(JSON.stringify(error))
});
}
main.init();
$("#btn-save').on('click')
- btn-save라는 id를 가진 요소를 클릭했을시 save함수를 실행하는 이벤트리스너를 등록
save : function ()
- 클릭 시 실행되는 save 함수
- title, content, author 의 값들을 data객체에 담아준다
$.ajax
- POST 방식으로 받아오며 json타입의 데이터를 받아 stringify로 문자열로 바꿔준다
.done()
- 성공했을 경우 글이 등록되었다는 알람을 띄우며 인덱스 페이지로 이동
.fail()
- 실패했을 경우 error를 문자열로 바꿔 알람을 띄운다