서버구조 정리
AddCartServlet → 장바구니 담기 / 신규 상품 추가
UpdateCartItemCountServlet → 장바구니 상품 수량 변경
DeleteCartServlet → 장바구니 상품 삭제
지금부터 비동시 처리 (AJAX)로 페이지 새로고침 없이
1. 수량 변경 (+/-)
2. 상품 삭제
3. 총액 업데이트
4. 장바구니 재랜더링
을 해보고자 합니다
<script>
const cartbody = $("#cart-tbody");
const totalPrice = $(".cart-summary p.mb-0"); // 변수 이름 통일
// 수량 변경 (+/-)
$(document).on("click", ".btn-minus, .btn-plus", function(){
const tr = $(this).closest("tr");
const cartPk = tr.data("cartpk");
const input = tr.find("input");
let count = parseInt(input.val());
if($(this).hasClass("btn-minus")) count = Math.max(1, count - 1);
else count += 1;
$.ajax({
url: "${pageContext.request.contextPath}/UpdateCartItemCountServlet",
type: "POST",
data: { cartPk: cartPk, newCount: count },
success: function(res){
if(res === "updateCartItemCountSuccess"){
input.val(count);
updateTotalPrice();
} else {
alert("수량 변경 실패");
}
}
});
});
// 삭제 버튼
$(document).on("click", ".cart-remove-btn", function(){
const tr = $(this).closest("tr");
const cartPk = tr.data("cartpk");
$.ajax({
url: "${pageContext.request.contextPath}/DeleteCartServlet",
type: "POST",
data: { cartPk: cartPk },
success: function(res){
if(res === "deleteToCartItemSuccess"){
tr.remove();
updateTotalPrice();
} else {
alert("삭제 실패");
}
}
});
});
// 총 금액 계산
function updateTotalPrice(){
let total = 0;
$("#cart-tbody tr").each(function(){
const priceText = $(this).find("td:eq(1)").text().replace("원","").replace(/,/g,"");
const count = parseInt($(this).find("input").val());
total += parseInt(priceText) * count;
});
totalPrice.text(total.toLocaleString("ko-KR") + "원");
}
// 페이지 로딩 시 총 금액 계산
$(document).ready(function(){
updateTotalPrice();
});
</script>
이렇게 해서 수량변경, 삭제, 총 금액을 계산할 때 AJAX로 로딩이 됩니다
jsp
<!-- 장바구니 품목 Start -->
<div class="container-fluid py-5 cart-section">
<div class="container py-5">
<div class="row">
<!-- 왼쪽 장바구니 테이블 -->
<div class="col-lg-8 col-md-7 col-sm-12 mb-5">
<div class="table-responsive card cart-table">
<table class="table">
<thead>
<tr>
<th scope="col">상품명</th>
<th scope="col">가격</th>
<th scope="col">수량</th>
<th scope="col">합계</th>
<th scope="col">삭제</th>
</tr>
</thead>
<tbody id="cart-tbody">
<!-- 상품 출력 -->
<c:forEach var="cart" items="${cartDatas}">
<tr data-cartpk="${cart.cartPk}">
<th scope="row">
<p class="mb-0 py-4">${cart.itemName}</p>
</th>
<td class="item-price">
<p class="mb-0 py-4">${cart.totalPrice}원</p></td>
<td>
<div class="input-group quantity py-4 cart-quantity" style="width: 100px;">
<button class="btn btn-sm btn-minus rounded-circle bg-light border">
<i class="fa fa-minus"></i>
</button>
<input type="text" class="form-control form-control-sm text-center border-0"
value="${cart.count}">
<button class="btn btn-sm btn-plus rounded-circle bg-light border">
<i class="fa fa-plus"></i>
</button>
</div>
</td>
<td class="item-total"><p class="mb-0 py-4">${cart.totalPrice}원</p></td>
<td class="py-4">
<button class="btn btn-md rounded-circle bg-light border cart-remove-btn">
<i class="fa fa-times text-danger"></i>
</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<!-- 오른쪽 결제요약 박스 -->
<div class="col-lg-4 col-md-5 col-sm-12">
<div class="bg-light rounded cart-summary">
<div class="p-4">
<h2 class="display-6 mb-4">장바구니 <span class="fw-normal">총액</span></h2>
</div>
<div class="py-4 mb-4 border-top border-bottom d-flex justify-content-between">
<h5 class="mb-0 ps-4 me-4">총 합계</h5>
<p class="mb-0 pe-4 total-price">${totalPrice}원</p>
</div>
<button class="btn btn-primary rounded-pill px-4 py-3 text-uppercase mb-4 ms-4 cart-buy-btn"
type="button">
구매
</button>
</div>
</div>
</div>
</div>
</div>
<!-- 장바구니 품목 End -->
이렇게 하면
기존 JSP 장바구니 페이지를 AJAX로 변경하여
수량변경, 장바구니 상품 삭제, 총액 업데이트를 페이지 새로고침 없이 볼 수 있습니다
정리하면
UpdateCartItemCountServlet 에서는
장바구니 상품 수량을 변경하는데
POST 요청으로 cartPk, newCount를 받아 DB에 보내 업데이트 합니다
성공/실패 메시지를 반환합니다
DeleteCartServlet 에서는
장바구니 상품 삭제를 하는데
POST 요청으로 cartPk를 받아 삭제를 진행합니다
성공/실패 메시지를 반환합니다
'🎅 오너먼트 프로젝트' 카테고리의 다른 글
| 결제 API (with 페이 디벨롭퍼) (0) | 2025.12.28 |
|---|---|
| 주소를 로그하지 못하였습니다 (0) | 2025.12.27 |
| 상품 상세 보기에서 "바로 구매" 시 빈문자열로 넘어오는 a태그 (0) | 2025.12.24 |
| JDBC 오너먼트 프로젝트용 계정 생성하고 사용해보기 (0) | 2025.12.22 |
| tags 폴더에 header, footer 만들어 호출해보기 (0) | 2025.12.17 |