[내일배움캠프] #211029 💻 TIL 💻

이수영·2021년 10월 31일
0

MY TIL 

목록 보기
28/50
post-thumbnail

📚 TIL

📌 4주차 타임어택 구현 테스트 복습

일단 후기 paging은 구글링해서 막 복붙했는데 어떻게 할 지 전혀 감이 안오더라 전혀 ... ^^
서버에서 처리해야할지 프론트에서 처리해야할지 궁금했는데 튜터님이 올려주신 코드를 보고 아하 했다 ,,ㅎㅎ
튜터님이 올려주신 코드에 내 주석을 적어보며 이해하기 !

✔ 페이징

  • 서버에서 post를 보여줄 때 조건 추가
  • app.py get_posts 전체코드
@app.route('/articles', methods=['GET'])
def get_posts():
    order = request.args.get('order')
    per_page = request.args.get('perPage') #page마다 몇개 post
    cur_page = request.args.get('curPage') #현재 page
    search_title = request.args.get('searchTitle')#search 제목
    search_condition = {}
    if search_title is not None:
        search_condition = {"title": {"$regex": search_title}}

    limit = int(per_page)
    skip = limit * (int(cur_page) - 1) #생략할 데이터 갯수
    
    total_count = db.article.find(search_condition).count()
    total_page = int(total_count / limit) + (1 if total_count % limit > 0 else 0)

    if order == "desc":
        articles = list(db.article.find(search_condition, {'_id': False})
                        .sort([("read_count", -1)]).skip(skip).limit(limit))
    else:
        articles = list(db.article.find(search_condition, {'_id': False})
                        .sort([("reg_date", -1)]).skip(skip).limit(limit))

    for a in articles:
        a['reg_date'] = a['reg_date'].strftime('%Y.%m.%d %H:%M:%S')

    paging_info = {
        "totalCount": total_count,
        "totalPage": total_page,
        "perPage": per_page,
        "curPage": cur_page,
        "searchTitle": search_title
    }

    return jsonify({"articles": articles, "pagingInfo": paging_info})

  • 다음페이지
 limit = int(per_page)#page마다 갯수 
 skip = limit * (int(cur_page) - 1) #생략할 데이터 갯수(다음페이지에선 안보여야됨)
    
 total_count = db.article.find(search_condition).count()
 total_page = int(total_count / limit) + (1 if total_count % limit > 0 else 0)
 #총 게시물이 22개인데 한 페이지에 5개의 게시물을 보여줄거라면 5개의 페이지가 필요하므로 총 페이지 갯수+1을 해야한다는 뜻

-index.html

         function showArticles(curPage) 
         {
                    let searchTitle = $("#searchTitle").val();
                    $.ajax({
                        type: "GET",
                        url: `/articles?perPage=${perPage}&curPage=${curPage}&order=${order}&searchTitle=${searchTitle}`,
                        data: {},
                        success: function (response) {
                            $("#list-post").empty();
                            let articles = response["articles"];
                            let pagingInfo = response["pagingInfo"];
                            for (let i = 0; i < articles.length; i++) {
                                let num = response["pagingInfo"]["totalCount"] - (perPage * (curPage - 1)) - i
                                makeListPost(articles[i], num);
                            }
                            makePaging(pagingInfo);
                        }
                    })
        }

        function makePaging(pagingInfo) 
        {
            let tempHtml = '';
            for (let i = 0; i < pagingInfo['totalPage']; i++) {
                if (i + 1 == pagingInfo['curPage']) {
                    tempHtml += `<li class="page-item active"><a class="page-link" href="#">${i + 1}</a></li>`;
                } else {
                    tempHtml += `<li class="page-item"><a class="page-link" href="#" onclick="showArticles(${i + 1})">${i + 1}</a></li>`;
                }
            }
            $("#pagination").html(tempHtml); #pagination 부분을 위의 temphtml로 바꿈
        }
profile
Hongik Univ 💻

0개의 댓글