본문 바로가기
Spring/JPA + Security

[Spring Data JPA] 구독하기 구현하기 - 2 Ajax 연결하기

by pyogowoon 2023. 1. 11.

Profile.jsp

<c:choose>

<c:when test="${dto.pageOwnerState}">
   <button class="cta" onclick="location.href='/image/upload'">사진등록</button>
</c:when>
<c:otherwise>
<c:choose>

<c:when test= "${dto.subscribeState}">
<button class="cta blue" onclick="toggleSubscribe(${dto.user.id}, this)">구독취소</button>
</c:when>
<c:otherwise>

<button class="cta" onclick="toggleSubscribe(${dto.user.id}, this)">구독하기</button>

</c:otherwise>

</c:choose>

</c:otherwise>

</c:choose>

 

 

이전에 c:choose 했었던 구독버튼 온클릭 이벤트에 ${dto.user.id} , 함수를 바로 불러오는 this를 추가

 

SusbcribeApiController

@RequiredArgsConstructor
@RestController
public class SubscribeApiController {


    private final SubscribeService subscribeService;

    @PostMapping("/api/subscribe/{toUserId}")
    public ResponseEntity<?> subscribe(@AuthenticationPrincipal PrincipalDetails principalDetails , @PathVariable int toUserId ){
        subscribeService.구독하기(principalDetails.getUser().getId(),toUserId);
        return new ResponseEntity<>(new CMRespDto<>(1, "구독하기 성공", null), HttpStatus.OK);
    }

    @DeleteMapping("/api/subscribe/{toUserId}")
    public ResponseEntity<?> unsubscribe(@AuthenticationPrincipal PrincipalDetails principalDetails , @PathVariable int toUserId ){
        subscribeService.구독취소하기(principalDetails.getUser().getId(), toUserId);
        return new ResponseEntity<>(new CMRespDto<>(1, "구독취소하기 성공", null), HttpStatus.OK);
    }
}

 

 이전에 만들어놓은 구독하기 로직의 맵핑주소를 토대로 Ajax를 만들어준다.

 

 

 

// (1) 유저 프로파일 페이지 구독하기, 구독취소
function toggleSubscribe(toUserId, obj) {
   if ($(obj).text() === "구독취소") {

    $.ajax({
        type: "delete",
        url: "/api/subscribe/"+toUserId,
        dataType: "json"
    }).done(res=>{
        $(obj).text("구독하기");
        $(obj).toggleClass("blue");
    }).fail(error=>{
            console.log("구독취소실패", error);
    });

   } else {

    $.ajax({
            type: "post",
            url: "/api/subscribe/"+toUserId,
            dataType: "json"
        }).done(res=>{
            $(obj).text("구독취소");
         $(obj).toggleClass("blue");
        }).fail(error=>{
                console.log("구독하기실패", error);
        });



   }
}

profile.js에 ajax문을 추가하고. 

  this로 obj를 받아오고 , 세션값인 ${dto.user.id} 로 toUserId 사용하여 url을 받았다.

별다른 입력값이 없기때문에 ajax는 type, url, dataType 정도면 해결.

 

 

구독하기 와 구독취소가 정상적으로 실행된다.

댓글