클라이언트 부분에서 검색 기능을 구현한 것을 적어보겠다!
home.hbs는 메인 화면
| home.hbs
{{!-- 검색창 --}}
<div id="search-field" class="field has-addons">
<div class="control has-icons-left" style=" 100%;">
<input id="search-input" class="input" type="input" placeholder="Search" onkeyup="enterkeySearch()">
<span class="icon is-small is-left">
<i class="fas fa-search"></i>
</span>
</div>
<div id="btn-search-post" class="control" onclick="searchPost()">
<button class="button is-sparta">검색</button>
</div>
</div>
onkeyup="enterkeySearch()"
를 적용해주었다.| home.js
// 검색창에서 엔터치면 searchPost()실행
window.enterkeySearch = () => {
if (window.event.keyCode == 13) {
searchPost();
}
};
...
// 검색
window.searchPost = () => {
$('#home-section-post').empty();
let searchQuery = $('#search-input').val();
if (searchQuery == '') {
alert('검색어를 입력해주세요!');
$('#search-input').focus();
return;
}
$.ajax({
type: 'GET',
url: process.env.BACKEND_HOST + '/post/search?query=' + searchQuery,
success: function (response) {
console.log(response);
let posts = response;
for (let index = 0; index < posts.length; index++) {
let id = posts[index]['id'];
let title = posts[index]['title'];
let meetingType = posts[index]['meetingType'];
let period = posts[index]['period'];
let hits = posts[index]['hits'];
let recruitmentState = posts[index]['recruitmentState'] ? '모집 완료' : '모집 중';
let recruitmentStateColor = posts[index]['recruitmentState'] ? 'is-default' : 'is-pink';
let recruitmentStateColorBack = posts[index]['recruitmentState'] ? 'is-white' : 'is-gray';
let cardHTML = `<div id=${id} class="card ${recruitmentStateColorBack}">
<div class="card-header">
<p class="card-header-title" onclick="openPost(${id})">${title}</p>
<div class="content bookmark">
<i class="fa-regular fa-bookmark" onclick="registerBookmark(${id})"></i>
</div>
</div>
<div class="card-content" onclick="openPost(${id})">
<div class="card-content-box">
<div class="content">
<span>기간</span>
<span class="bubble-item bubble">${period}</span>
</div>
<div class="content">
<span>모임 방식</span>
<span class="bubble-item bubble">${meetingType}</span>
</div>
<div class="content">
<span>모집 현황</span>
<span class="bubble-item ${recruitmentStateColor}">${recruitmentState}</span>
</div>
</div>
<div class="card-content-box">
<div>
<div class="content">
<i class="fa-regular fa-eye"></i>
<span>${hits}</span>
</div>
</div>
</div>
</div>
</div>`;
$('#home-section-post').append(cardHTML);
}
resizeHomeContainer();
}
});
};
query
변수로 서버로 넘어가게 되고, 요청이 성공하면 서버로부터 받은 데이터를 그려준다제목에 '스프링'단어가 포함된 게시글이 검색되는 것을 확인할 수 있다!