본문 바로가기
JAVASCRIPT & JQUERY

AJAX 페이징 구현 방법!! (영상 有)

by GoodDayDeveloper 2022. 2. 16.
반응형


안녕하세요. 오늘은 AJAX로 페이징 처리하는 방법에 대해 이야기해보겠습니다.
저는 자바를 기반으로한 AJAX 페이징 처리 방법을 정리하였습니다.

우선 AJAX 에 대해 이야기해보겠습니다.

Ajax란  


Asynchronous JavaScript and XML의 약자이며,
빠르게 동작하는 동적인 웹 페이지를 만들기 위한 개발 기법 중 하나입니다.

Ajax는 웹 페이지 전체를 다시 로딩하지 않고도, 웹 페이지의 일부분만을 갱신할 수 있습니다.
즉, Ajax를 이용하면 백그라운드 영역에서 서버와 통신하여, 그 결과를 웹 페이지의 일부분에만 표시할 수 있습니다.

여기서 일부분만 표시할 수 있다는 것이 포인트입니다.

AJAX 적용 전과 후를 나눠봤습니다.

AJAX 적용 전

 

 

페이지 버튼을 누를때마다 계속해서 페이지 로딩이 되버립니다...
이럴 경우 페이지가 자꾸 상단으로 올라가기 때문에 사용자 입장에서는 불편할 수가 있습니다.
(영상을 기재하려 하였으나 로딩되는 영상은 왠지 제한이 되어 올릴 수가 없네요..)



AJAX 적용 후


페이지 버튼을 누를 경우 테이블과 페이지 버튼 영역만 변경되기때문에
사용자 입장에서는 편리하게 서비스를 이용할 수 있겠지요!



제 블로그에 페이징 하는 글이 있습니다.
처음부터 다 정리하면 너무 많기 때문에 기본적인 페이징 구조 및 SQL쪽은 이쪽글을 참고 부탁드립니다.
https://chobopark.tistory.com/170

 

Spring 홈페이지 - (13) 게시판 페이징 작업

(페이징 버튼 클릭 시, 활성화 기능을 추가하였습니다. 2021년 5월 13일) 오늘은 게시판 페이징을 해보겠습니다. 제가 한 방식은 전자정부프레임워크에서 사용되는 방식을 변형하여 만들었습니다.

chobopark.tistory.com

 



HTML

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
<div class="mapCon2  wow slideInUp">
<div class="mCont_scroll">
<table class="tblMemSearch">
<caption>회원사 검색 리스트</caption>
<colgroup>
    <col style="width:10%;">
    <col style="width:10%;">
    <col style="width:10%;">
    <col style="width:30%;">
    <col style="width:20%;">
    <col style="width:20%;">
</colgroup>
<thead>
    <tr>
        <th>순번</th>
        <th>시도</th>
        <th>시구군</th>
        <th>업체명</th>
        <th>성명</th>
        <th>전화번호</th>
    </tr>
</thead>
<tbody class="listData">
<c:set var="ii" value="${resultCnt - (searchVO.pageIndex -1) * paginationInfo.recordCountPerPage }" />
<c:forEach var="result" items="${resultList}" varStatus="sts">
    <tr class="memList">
        <td class="t_c"><c:out value="${ii}" /></td>
        <td class="t_c"><c:out value="${result.me_sido}" /></td>
        <td><c:out value="${result.me_gugun}" /><button type="button" class="btnInfo fr"></button></td>
        <td class="t_c"><c:out value="${result.me_biz_name}" /></td>
        <td class="t_c"><c:out value="${result.me_name}" /></td>
        <td class="t_c"><c:out value="${result.me_biz_tel}" /></td>
    </tr>
    <c:set var="ii" value="${ii - 1}" />
</c:forEach>
<c:if test="${fn:length(resultList) == 0">
<tr>
    <td colspan="6"  class="first last">조회 결과가 없습니다.</td> 
</tr>
</c:if>
</tbody>
</table>
</div>
 
 
<div class="board-list-paging fr">
<c:set var="pageIndex" value="1"/>
<ol class="pagination" id="pagination">
<c:if test="${searchVO.prev}">
<li class="prev_end">
       <a href="javascript:void(0);" onclick="fn_go_page(1); return false;" ></a>
    </li>
<li class="prev">
<a href="javascript:void(0);"  onclick="fn_go_page(${searchVO.startDate - 1}); return false;" ></a>
</li>
</c:if>
<c:forEach var="num" begin="${searchVO.startDate}" end="${searchVO.endDate}">
<li>
<a href="javascript:void(0);" onclick="fn_go_page(${num}); return false;" class="num ${pageIndex eq num ? 'on':'' }" title="${num}">${num}</a>
</li>
</c:forEach>  
<c:if test="${searchVO.next}">
<li class="next">
<a href="javascript:void(0);"  onclick="fn_go_page(${searchVO.endDate + 1}); return false;" ></a>
</li>
<li class="next_end">
<a href="javascript:void(0);" onclick="fn_go_page(${searchVO.realEnd }); return false;"></a>
</li>
</c:if>     
</ol>
</div>
 
</div>
 
 
 
cs


HTML에서는 보통의 테이블과 비슷한 구조입니다.
여기서 AJAX 기반의 기능이기 때문에 스크립트 부분이 가장 중요합니다.
태그에 스크립트로 덮어주면 완성입니다. 굉장히 쉽습니다.
태그에 있는 fn_go_page란 함수에 AJAX를 적용하겠습니다!


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
@RequestMapping(value = "/gnb01/lnb06/snb03/areaListAjax.do")
@ResponseBody
public String select_snb03_ajax(
    @RequestBody String filterJSON,
    HttpServletResponse response,
    ModelMap model ) throws Exception {
 
JSONObject obj = new JSONObject();
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
 
try{            
  ObjectMapper mapper = new ObjectMapper();
  MemberVO searchVO = (MemberVO)mapper.readValue(filterJSON,new TypeReference<MemberVO>(){ });
  
  searchVO.setSite_code(loginService.getSiteCode());
 
  /* 페이징 시작 */
    Pagination paginationInfo = new Pagination();
    paginationInfo.setCurrentPageNo(searchVO.getPageIndex());        //현재 페이지 번호
    paginationInfo.setRecordCountPerPage(searchVO.getPageUnit());    //한 페이지에 게시되는 게시물 건수
    paginationInfo.setPageSize(searchVO.getPageSize());                //페이징 리스트의 사이즈
 
    searchVO.setFirstIndex(paginationInfo.getFirstRecordIndex());
    searchVO.setRecordCountPerPage(paginationInfo.getRecordCountPerPage());
 
    Map<StringObject> map = gnb01Service.getAearMemberList(searchVO);
    int totCnt = Integer.parseInt((String)map.get("resultCnt"));
    
    paginationInfo.setTotalRecordCount(totCnt);
    
    searchVO.setEndDate(paginationInfo.getLastPageNoOnPageList());
    searchVO.setStartDate(paginationInfo.getFirstPageNoOnPageList());
    searchVO.setPrev(paginationInfo.getXprev());
    searchVO.setNext(paginationInfo.getXnext());
    searchVO.setRealEnd(paginationInfo.getRealEnd());
    
    /* 페이징 끝 */
    
    obj.put("resultList", map.get("resultList"));
    obj.put("resultCnt", map.get("resultCnt"));
    obj.put("totalPageCnt", (int)Math.ceil(totCnt / (double)searchVO.getPageUnit()));
    obj.put("searchVO", searchVO);
  
}catch(Exception e){
  System.out.println(e.toString());
  obj.put("res""error");
  
  }
 
out.print(obj);
return null;
 
}
cs


컨트롤러에서 Pagination 클래스와 페이징 변수들을 계산하여 데이터를 출력합니다.
아래는 Pagination 클래스와 페이징 변수 및 관련 SQL 글입니다. 꼭 참고하세요!!
(스크립트(제이쿼리) 부분만 참고하실거면 참고 안하셔도 괜찮습니다.)
https://chobopark.tistory.com/170

 

Spring 홈페이지 - (13) 게시판 페이징 작업

(페이징 버튼 클릭 시, 활성화 기능을 추가하였습니다. 2021년 5월 13일) 오늘은 게시판 페이징을 해보겠습니다. 제가 한 방식은 전자정부프레임워크에서 사용되는 방식을 변형하여 만들었습니다.

chobopark.tistory.com

 

반응형





JQuery (script)

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
<script type="text/javascript">
 
function fn_go_page(pageNo) {
 
var submitObj = new Object();
 
submitObj.pageIndex= pageNo;
submitObj.searchWrd= $("#searchWrd").val();
 
$.ajax({ 
url: path+"/gnb01/lnb06/snb03/areaListAjax.do"
type: "POST"
contentType: "application/json;charset=UTF-8",
data:JSON.stringify(submitObj),
dataType : "json",
progress: true
}) 
.done(function(data) {
    
    var  result = new Array;
    result = data.resultList;
    var searchVO = data.searchVO;
    var realEnd = searchVO.realEnd;
    var startDate = searchVO.startDate;
    var startButtonDate = startDate - 1;
    var endDate = searchVO.endDate;
    var endButtonDate = endDate + 1;
    var pageIndex = searchVO.pageIndex;
    var resultCnt = data.resultCnt;
    var totalPageCnt = data.totalPageCnt;
    var recordCountPerPage = searchVO.recordCountPerPage;
    
    
    var ii = (resultCnt - (pageIndex - 1* recordCountPerPage);
    
    var content = '';
    var content2 = '';
    
    $.each(result, function(key, value) {
        
        content +=    '<tr class="memList">';
        content +=    '<td class="t_c">' + ii + '</td>';
        content +=    '<td class="t_c">' + value.me_sido + '</td>';
        content +=    '<td>' + value.me_gugun + '<button type="button" class="btnInfo fr"></button></td>';
        content +=    '<td class="t_c">' + value.me_biz_name + '</td>';
        content +=    '<td class="t_c">' +  value.me_name  +'</td>';
        content +=    '<td class="t_c">' +  value.me_biz_tel + '</td>';
        content +=    '</tr>';
         ii--;
      });
    
    $(".listData").html(content);    
    
    content2 = '<input type="hidden" id="pageIndex" name="pageIndex" value="1">';
    content2 +=    '<ol class="pagination" id="pagination">';
    
    if(searchVO.prev){
        content2 +=    '<li class="prev_end"><a href="javascript:void(0);" onclick="fn_go_page(1); return false;" ></a></li>';    
        content2 +=    '<li class="prev"><a href="javascript:void(0);"  onclick="fn_go_page(' + startButtonDate + '); return false;" ></a></li>';    
    }
    
    for (var num=startDate; num<=endDate; num++) {
         if (num == pageIndex) {
             content2 +=    '<li><a href="javascript:void(0);" onclick="fn_go_page(' + num + '); return false;" title="' + num + '"  class="num on">' + num + '</a></li>';
         } else {
             content2 +=    '<li><a href="javascript:void(0);" onclick="fn_go_page(' + num + '); return false;" title="' + num + '" class="num">' + num + '</a></li>';
         }
    }
    
    if(searchVO.next){
        content2 +=    '<li class="next"><a href="javascript:void(0);"  onclick="fn_go_page(' + endButtonDate + '); return false;" ></a></li>';    
        content2 +=    '<li class="next_end"><a href="javascript:void(0);" onclick="fn_go_page(' + searchVO.realEnd +'); return false;"></a></li>';    
    }
    
    content2 +=    '</ol>';
    content2 +=    '</div>';
 
    $(".board-list-paging").html(content2);
    
 }) 
 .fail(function(e) {  
     alert("검색에 실패하였습니다.");
 }) 
 .always(function() { 
     
 }); 
}
 
</script>
cs


함수의 매개변수로 받은 페이지 번호(pageNo)를 서버에 가지고 갑니다.
테이블 리스트는 result 변수에 저장하고
나머지 페이징에 필요한 부분들을 변수에 담습니다.

그리고 content에는 테이블의 내용, content2에는 페이징 영역을 담을겁니다.
반복문을 통해서 내용을 담은 다음에 태그의 클래스 부분(listData)에 html 메서드를 통해 덮어줍니다.
패이징 부분도 html 태그와 똑같이 content2에 작성한 다음, board-list-paging의 클래스에 덮어주면 끝입니다.

처음 접하면 쉬우면서도 조금 해깔린 부분이 많습니다.
궁금한점 있으시면 말씀해주세요~

반응형

댓글