Day 8
๊ฒ์๊ธ ์์ , ์ญ์ ํ๋ฉด ๋ง๋ค๊ธฐ
์์ API๋ ์ด๋ฏธ ๋ง๋ค์ด๋์์
๊ฒ์๊ธ ์์ ํ๋ฉด mustache ํ์ผ์ ์์ฑ
src/main/resources/templates/posts-update.mustache
{{>layout/header}}
<h1>๊ฒ์๊ธ ์์ </h1>
<div class="col-md-12">
<div class="col-md-4">
<form>
<div class="form-group">
<label for="title">๊ธ ๋ฒํธ</label>
<input type="text" class="form-control" id="id" value="{{post.id}}" readonly>
</div>
<div class="form-group">
<label for="title">์ ๋ชฉ</label>
<input type="text" class="form-control" id="title" value="{{post.title}}">
</div>
<div class="form-group">
<label for="author"> ์์ฑ์ </label>
<input type="text" class="form-control" id="author" value="{{post.author}}" readonly>
</div>
<div class="form-group">
<label for="content"> ๋ด์ฉ </label>
<textarea class="form-control" id="content">{{post.content}}</textarea>
</div>
</form>
<a href="/" role="button" class="btn btn-secondary">์ทจ์</a>
<button type="button" class="btn btn-primary" id="btn-update">์์ ์๋ฃ</button>
<button type="button" class="btn btn-danger" id="btn-delete">์ญ์ </button>
</div>
</div>
{{>layout/footer}}
{{post.id}}
mustache๋ ๊ฐ์ฒด์ ํ๋์ ์ ๊ทผ ์ . ์ผ๋ก ๊ตฌ๋ถํ๋ค
Postํด๋์ค์ id์ ๋ํ ์ ๊ทผ์ post.id ์ด๋ ๊ฒ ์์ฑํ๋ค
readonly
input ํ๊ทธ์ ์ฝ๊ธฐ ๊ฐ๋ฅ๋ง ํ์ฉํ๋ ์์ฑ
id์ author๋ ์์ ํ ์ ์๋๋ก ์ฝ๊ธฐ๋ง ํ์ฉํ๋๋ก ์ถ๊ฐ
btn-update ๋ฒํผ์ ๋๋ฅด๋ฉด update ๊ธฐ๋ฅ์ ํธ์ถํ ์ ์๋๋ก index.js ํ์ผ์๋ update function์ ์ถ๊ฐ
src/resources/static/js/app/index.js
init : function () {
var _this = this;
$('#btn-save').on('click', function () {
_this.save();
});
$('#btn-update').on('click', function(){
this.update();
});
},
...
update : function(){
var data = {
title: $('#title').val(),
content: $('#content').val()
};
var id = $('#id').val();
$.ajax({
type: 'PUT',
url: '/api/v1/posts/'+id,
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))
});
}
$('#btn-update').on('click')
btn-update๋ผ๋ id๋ฅผ ๊ฐ์ง HTML element์ click ์ด๋ฒคํธ๊ฐ ๋ฐ์ํ ๋ update function์ ์คํํ๋ผ๊ณ ๋ฑ๋กํด๋
์ด๋ฒคํธ ๋ฑ๋ก
type: 'PUT'
HTTP Method์ค์ PUT๋ฉ์๋
PostsApiController์ ์๋ API์์ ์ด๋ฏธ @PutMapping์ผ๋ก ์ ์ธํ๊ธฐ ๋๋ฌธ์ PUT์ ์ฌ์ฉํด์ผํจ
REST์์๋ CRUD๋ฅผ HTTP Method์ ๋งคํํ์
Create - POST
Read - GET
Update - PUT
Delete - DELETE
url:'/api/v1/posts/'+id
์ด๋ ๊ฒ์๊ธ์ ์์ ํ ์ง URL Path์ผ๋ก ๊ตฌ๋ถํ๊ธฐ ์ํด Path์ id๋ฅผ ์ถ๊ฐ
๋ง์ง๋ง์ผ๋ก ์ ์ฒด ๋ชฉ๋ก์์ ์์ ํ์ด์ง๋ก ์ด๋ํ ์ ์๊ฒ ํ์ด์ง ์ด๋ ๊ธฐ๋ฅ์ ์ถ๊ฐ
src/main/resources/templates/index.mustache
{{#posts}}
<tr>
<td>{{id}}</td>
<td><a href="/posts/update/{{id}}">{{title}}</a></td>
<td>{{author}}</td>
<td>{{modifiedDate}}</td>
</tr>
{{/posts}}
- ํ์ดํ์ ํด๋ฆญํ๋ฉด ํด๋น ๊ฒ์๊ธ์ ์์ ํ๋ฉด์ผ๋ก ์ด๋
Last updated
Was this helpful?