좋아요 기능 구현중.
<div class="link-inner">
<a id="likeBtn" href="` + list[i].bno + `">`;
if(data !== null) {
if(data.includes(list[i].bno)) {
str += `<img src="<c:url value='/img/like2.png' />" alt="like2"> 좋아요</a>`;
} else {
str += `<img src="<c:url value='/img/like1.png' />" alt="like1"> 좋아요</a>`;
}
} else {
str += `<img src="<c:url value='/img/like1.png'/>" alt="like1"> 좋아요</a>`;
}
str += `
<a id="regist" href="` + list[i].bno +`"><i class="glyphicon glyphicon-comment"></i>댓글달기</a>
<a id="delete" href="` + list[i].bno +`"><i class="glyphicon glyphicon-remove"></i>삭제하기</a>
</div>
id=ContentDiv에 쌓인 a id=likeBtn > img 태그를 클릭하면 정상적으로 js 로직및 span 태그에 나타나는 좋아요 개수가 정상적으로 동작하지 않았다.
$('#contentDiv').on('click', 'a', function(e) {
e.preventDefault();
console.log($(this).attr('id'));
if(e.target.getAttribute('alt') === 'like1' && e.target.getAttribute('alt') === 'like2'){
return;
}
if(!($(this).attr('id') === 'likeBtn' || e.target.getAttribute('alt')=== 'like2') || e.target.getAttribute('alt')=== 'like1') {
console.log('좋아요 버튼이 아님!');
return;
}
console.log('좋아요 버튼 클릭!' + $(this));
console.log($(this).attr('src')!='');
const $btn = e.target;
const bno = $(this).attr('href');
const id = '${login.userid}';
if(id === '') {
alert('로그인 안했구나?');
return;
}
$.ajax({
type: 'post',
url: '<c:url value="/promo/like" />',
contentType: 'application/json',
data: JSON.stringify({
'bno' : bno,
'userid' : id
}),
success: function(result) {
console.log(result);
if(result === 'like') {
e.target.firstChild.setAttribute('src', '/img/like2.png');
const $likeCnt = e.target.parentNode.previousElementSibling.children[1];
console.log($likeCnt);
$likeCnt.textContent = Number($likeCnt.textContent) + 1;
} else {
e.target.firstChild.setAttribute('src', '/img/like1.png');
const $likeCnt = e.target.parentNode.previousElementSibling.children[1];
console.log($likeCnt);
$likeCnt.textContent = Number($likeCnt.textContent) - 1;
}
},
error: function() {
alert('좋아요 진행 에러!');
}
});
}); //end 좋아요 처리.
간단하게 클릭한 타겟이 img라면 alt 속성을 가져와서 like1,like2와 같다면
좋아요 함수를 return 시켜 주었더니 해결했다.
SQL
<bestCafe>
SELECT bno, COUNT(*),
ROW_NUMBER() OVER(ORDER BY COUNT(*) DESC) AS RANK
FROM promoboardlike
GROUP BY bno
HAVING count(*) > 0
AND count(*) < 5
얻어온 bno(pk)로 게시물을 가지고 오는 로직
<getRanked>
SELECT pr.*,
u.filenum
FROM promoboard pr
LEFT JOIN users u
ON pr.writer = u.username
WHERE bno = #{bno}
bestCafe ->
List<PromoLikeVO> promoLike = promoBoardService.bestCafe();
getRanked ->
List<PromoBoardVO> boardList = new ArrayList<>();
for(PromoLikeVO pvo : promoLike) {
boardList.add(promoBoardService.getRanked(pvo.getBno()));
System.out.println(pvo.getBno());
System.out.println("배열 담는중" + pvo);
}
System.out.println(boardList);
model.addAttribute("rank",boardList);
게시물 5개를 가져와서 jsp단에 뿌려주었다.