본문 바로가기

SpringBoot/스파르타 웹개발의 봄 spring

[스파르타 웹개발의 봄 spring] 04.13 관심 상품 보여주기

728x90
반응형

##$(document).ready 함수의 의미

:페이지가 모두 로드된 직후 실행할 자바스크립트 코드를 넣는 곳입니다. 일단 접속하면 관심 상품을 보여주어야 하기 때문에 showProduct 함수를 호출하고 있습니다.

 

##showProduct

-등록된 관심상품 목록 가져오기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function showProduct() {
    /**
     * 관심상품 목록: #product-container
     * 검색결과 목록: #search-result-box
     * 관심상품 HTML 만드는 함수: addProductItem
     */
    // 1. GET /api/products 요청
    $.ajax({
        type: "GET",
        url: "/api/products",
        success: function (response){ // List<product> 리스트를 get해옴
            // 2. 관심상품 목록, 검색결과 목록 비우기
            console.log("get finish")
            $('#product-container').empty();
            $('#search-result-box').empty();
            // 3. for 문마다 관심 상품 HTML 만들어서 관심상품 목록에 붙이기!
            for(let i=0;i< response.length;i++){
                let product = response[i];
                let tempHtml = addProductItem(product)
                $('#product-container').append(tempHtml); // html추가
            }
        }
    })
 
}
cs

 

##addProductItem 

:가져온 관심상품을 html로 변환해 화면에 추가

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function addProductItem(product) {
    // link, image, title, lprice, myprice 변수 활용하기
    // 주의: 백틱으로 리턴
return `<div class="product-card" onClick="window.location.href='${product.link}'"> <!--상품링크 수정-->
        <div class="card-header">
            <img src="${product.image}"<!--상품이미지-->
                 alt="">
        </div>
        <div class="card-body">
            <div class="title">
                ${product.title}<!--상품이름 수정-->
            </div>
            <div class="lprice">
                <span>${numberWithCommas(product.lprice)}</span>원 <!--상품최저가 수정-->
            </div>
            <div class="isgood ${product.lprice < product.myprice ? '':'none'}"> <!--상품최저가 최신화 할 때 클래스 이름 2가지로 되게 함 수정-->
                최저가
            </div>
        </div>
    </div>`;
}
 
cs
반응형