[JavaScript] ajax와 ROWNUM을 통한 무한스크롤

리트리버J

·

2020. 11. 15. 19:05

728x90

1. SQL / myBatis mapper

부등호는 태그로 인식하여 에러가 나므로

<![CDATA[ 부등호 ]]>로 처리해준다.

 

Controller => Service => Dao => mapper 의 경로로 jsp에서 스크롤을 내릴때마다 start와 end에 +9를 

해주어 1~9 / 10~18 / 19~27 ... 이런 식으로 ROWNUM을 통해 DB에서 값을 가져온다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 상품 목록 불러오기 -->
<select id="getProductList" parameterType="hashmap" resultMap="productResultSet">
    SELECT *
    FROM
    (select rownum as rownumber, p.* from PRODUCT p
    JOIN GOODS_CATEGORY ON (CATENAME = PRODUCT_CATEONE)
    WHERE CATECODE = 10
    ) a
    WHERE a.rownumber <![CDATA[ >= ]]> #{start} AND a.rownumber <![CDATA[ <= ]]> #{end}
    <if test="what eq '인기순'.toString()">
        ORDER BY PRODUCT_COUNT DESC
    </if>
    <if test="what eq '가격순'.toString()">
        ORDER BY PRODUCT_PRICE
    </if>
</select>
cs

 

2. jsp의 ajax

 

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    <script>
    
        // 무한 스크롤
        var $doc=$(document);    
        var $win=$(window);
 
        let startPage = 10;
        let endPage = 18;
        let addStar = 0;
        let what = null;
        
        $(".selectbox").change(function(){
            what = $(".selectbox option:selected").val();
        });
        
        $(window).scroll(function(){ 
            if ($doc.height()-$win.height()-$(this).scrollTop() == 0) {
                let whatTemp = what;
                let navNo = ${categoryList}[0].cateCode;
                
                $.ajax({
                    url:"infinityScroll.do",
                    data:{
                        navNo:navNo,
                        startPage : startPage,
                        endPage : endPage,
                        what:whatTemp
                    },
                    dataType:"json",
                    success:function(data){
                        
                        $cmtWrap = $(".Lsit-Saction");
                        
                        var $divF; // 1단계
                        
                        var $inputS; // 2단계
                        var $aS; // 2-1단계
                        var $divS; // 2-2단계
                        
                        var $divImg; // 3단계
                        var $pT; // 3-1단계
                        var $divT;    // 3-2 단계
                        
                        var $imgP; // 4단계
                        var $imgR; // 4-1단계
                        var $spanN; // 4-2단계
                        var $spanS; // 4-3단계
                        var $spanSN; // 4-4단계
                        var $spanF; // 4-5단계
                        
                        var $spanC; // 5단계
                        var $imgbuy; // 5단계
                        
                        console.log(data);
 
                        if(data.length > 0){ // 게시글이 있을 경우
                            for(var i in data){
                                
                                $divF = $("<div class='productOne'>").addClass("product" + addStar); // 1단계
                                
                                $inputS = $("<input type='hidden' class='pCategory'>").attr("value",data[i].category); // 2단계 hidden category
                                $aS = $("<a class='thumbnail'>").attr("href""productDetail.do?no=" + data[i].no); // 2-1단계 a 태그
                                $divS = $("<div class='list_contents_marign'>"); // 2-2단계 div
                                
                                $divImg = $("<div class='list_img_div'>"); // 3단계 img container
                                $pT = $("<p class='font_noto list_explain_index'>").html(data[i].title); // 3-1단계 p태그 제목
                                $divT = $("<div>"); // 3-2단계 div 여러가지
                                
                                $imgP = $("<img class='list_contents_img_index'>").attr("src","resources/pUploadFiles/" + data[i].renamePic ); // 4단계 상품 사진
                                
                                $imgR = $("<img class='list_rank_index'>").attr("src","resources/img/lv1.png"); // 4단계 계급사진
                                $spanN = $("<span class='font_noto'>").html(data[i].nickName); // 4단계 닉네임
                                $spanS = $("<span class='list_star_container_index'>").addClass("list_star" + addStar); // 4단계 별 컨테이너
                                $spanSN = $("<span class='font_noto starNum'>").html("(" + parseFloat(data[i].star).toFixed(1+ ")").addClass("starclass" + addStar); // 4단계 별점
                                $spanF = $("<span>");    // 4단계 span 태그
                                
                                $spanC = $("<span class='font_noto'>").html(data[i].count + "명선택"); // 5단계 몇명 선택
                                $imgbuy = $("<img src='resources/img/buy.png' class='list_choice_img_index'>"); // 선택 이미지
                                
                                // ---------------------------------------------------
                                
                                $spanF.append($spanC); // 5단계 추가
                                $spanF.append($imgbuy); // 5단계 추가
                                
                                $divT.append($imgR); // 4단계 추가
                                $divT.append("&nbsp;");
                                $divT.append($spanN); // 4단계 추가
                                $divT.append("&nbsp;");
                                $divT.append($spanS); // 4단계 추가
                                $divT.append("&nbsp;");
                                $divT.append($spanSN); // 4단계 추가
                                $divT.append("&nbsp;");
                                $divT.append($spanF); // 4단계 추가
                                
                                $divImg.append($imgP); // 4단계 추가
                                
                                $aS.append($divImg); // 3단계 추가
                                $divS.append($pT); // 3단계 추가
                                $divS.append($divT); // 3단계 추가
                                
                                $divF.append($inputS); // 2단계 추가
                                $divF.append($aS); // 2단계 추가
                                $divF.append($divS); // 2단계 추가
                                
                                $cmtWrap.append($divF);
                            }
                        
                        }
                        
                        // 시작 페이지 ROWNUM + 9
                         startPage = startPage + 9;
                        // 끝 페이지  ROWNUM + 9
                         endPage  = endPage + 9
                        // 별 계산해주는 함수
                         addedStar("list_star" + addStar, ".product" + addStar, "starclass" + addStar);
                        // 로딩 될 때마다 불러오는 클래스 값 변경해주기.
                        addStar++;
                        
                        filter();
                         
                    },error:function(request,status,errorData){
                        console.log(request.status + ":" + errorData);
                    }
                });
            }
        });
    </script>
    
    <script>
        
        // 처음 9개 별 찍어주기
        addedStar('list_star_container_index''.productOne''starNum');
        
        // 매개변수를 통해 별 그려주는 함수
        // addedStar(추가해줄 클래스명, 추가 해야 할 갯수, 숫자값 클래스);
        function addedStar(appendPlace, productNum, starPoint){
            
            // appned 할 곳
            let starAppend = document.getElementsByClassName(appendPlace);
            // 상품의 갯수만큼 for문
            let pCount = $(productNum).length;
            // 숫자의 배열
            let sNumber = [];
 
            for (var i = 0; i < pCount; i++) {
                
                // 숫자로 변환해주기
                sNumber[i] = Number(document.getElementsByClassName(starPoint)[i].innerText.substring(1,4));
                
                // append 할 곳
                let star = starAppend[i]; 
                
                    // 정수가 아닌 소숫점일 때,
                    if(!Number.isInteger(sNumber[i])){
 
                        // ex) 3.5일 때     3.5-1 = 2.5 총 3번(0,1,2) 꽉찬별찍고 
                        for (var j = 0; j < sNumber[i]-1; j++) {
                            var iii = document.createElement("i");
                            iii.className = "fas fa-star"// 꽉찬별
                            star.appendChild(iii);
                        }
 
                        // 반별찍고   2 < 3.5 => 반별 하나 찍고
                        for (var l = j; l < sNumber[i]; l++) {
                            var lll = document.createElement("i");
                            lll.className = "fas fa-star-half-alt"// 반별
                            star.appendChild(lll);
                        }
                        // 5 - 3.5 - 1 => 0.5 빈별 찍고
                        for (var k = 0; k < 5 - sNumber[i] - 1; k++) {
                            var jjj = document.createElement("i");
                            jjj.className = "far fa-star"// 빈별
                            star.appendChild(jjj);
                        }
                
                    }else{
 
                        for (var j = 0; j < sNumber[i]; j++) {
                            var iii = document.createElement("i");
                            iii.className = "fas fa-star";
                            star.appendChild(iii);
                        }
 
                        for (var k = 0; k < 5 - sNumber[i]; k++) {
                            var jjj = document.createElement("i");
                            jjj.className = "far fa-star";
                            star.appendChild(jjj);
                        }
                    }
            }
        }
    </script>
cs

 

3. Controller

 

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    /** 1. 상품 리스트 메소드
     * @param model
     * @param navNo
     * @return
     */
    @RequestMapping(value = "productList.do", method = RequestMethod.GET)
    public String productList(Model model, int navNo, String what){
        List<ProductCategory> category = pService.categoryList(navNo);
        List<ProductCategory> category2 = pService.categoryList2(navNo);
 
        if(what == "최신순") {
            what = null;
        }
        
        System.out.println("정렬 순서 : " + what);
 
        String no = Integer.toString(navNo);
        String start = "1";
        String end = "9";
        
        HashMap<StringString> map = new HashMap<StringString>();
        
        map.put("no", no);
        map.put("start", start);
        map.put("end", end);
 
        map.put("no", no);
        map.put("what", what);
 
        List<Product> productList = pService.productList(map);
 
        model.addAttribute("categoryList", JSONArray.fromObject(category));
        model.addAttribute("categoryList2", JSONArray.fromObject(category2));
        model.addAttribute("productList", productList);
        model.addAttribute("what", what);
 
        return "user/product/productList";
    }
    
    /**
     * 1─1. 리스트 무한 스크롤
     * @throws JsonIOException
     * @throws IOException
     */
    @RequestMapping(value="infinityScroll.do", produces="application/json; charset=UTF-8")
    public void infinityScroll(HttpServletResponse response, int navNo, int startPage, int endPage, String what) throws JsonIOException, IOException {
        System.out.println("1분류 : " + navNo);
        System.out.println("시작페이지 : " + startPage);
        System.out.println("끝 페이지 : " + endPage);
        System.out.println("정렬 순서 : " + what);
        
        String no = Integer.toString(navNo);
        String start = Integer.toString(startPage);
        String end = Integer.toString(endPage);
        
        HashMap<StringString> map = new HashMap<StringString>();
        
        map.put("no", no);
        map.put("start", start);
        map.put("end", end);
        map.put("what", what);
        
        List<Product> scrollList = pService.productList(map);
        
        response.setContentType("application/json; charset=utf-8");
 
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        
        gson.toJson(scrollList,response.getWriter());
    }
cs

추가 궁금한 사항은 댓글 남겨주시면 답변해드리겠습니다.

728x90