pagination version up

Jiwontwopunch·2022년 1월 17일
0

TIL

목록 보기
29/92
post-thumbnail

list.html

주요 코드만, main.js, list.js 링크

const pageno = getPageno();
const url = 'http://sample.bmaster.kro.kr/contacts?pageno='
    + pageno + "pagesize=" + PAGE_SIZE;
$.ajax(url).done(result=>{
  // result: pageno, pagesize, totalcount, contacts
  const pagination = getPagination(result);
  printContacts(result.contacts);
  printPagination(pagination, pageno);
});

list.js

주요 코드만

const PAGE_SIZE = 10;
const PAGE_PER_BLCOK = 5;

// function getPageno() {}
const getPageno = () => {
  const index = location.search.indexOf('=');
  const param = location.search.substr(index+1);
  const pageno = parseInt(param);
  if(isNaN(pageno)==true){
    location.href = "list.html?pageno=1";
  } else return pageno;
}
const getPagination = (result) =>{
  let blockNo = Math.floor(result.pageno/PAGE_PER_BLOCK);
  if(result.pageno%PAGE_PER_BLOCK==0) blockNo--;
  const startPage = blcokNo *PAGE_PER_BLOCK +1;
  const prev = startPage -1;
  let endPage = startPage + PAGE_PER_BLOCK -1;
  let next = endPage +1;
  let countOfPage = Math.floor(result.totalcount/PAGE_SIZE)+1;
  if(result.totalcount%PAGE_SIZE==0) countOfPage--;
  if(endPage>=countOfPage){
    endPage = countOfPage;
    next = 0;
  }
  // 구조 분해 할당
  return { prev, startPage, endPage, next };
}

// 정적 분석 : ESLint, SonarLint...
const printContacts = (contacts) =>{
  const $list = $('#list');
  // for(let i=?; ;) : 배열의 인덱스 값
  // for(ob of ar) : 배열의 원소를 하나씩 꺼내면서
  // $.each(배열, function(idx,원소) {})
  // : 인덱스와 원소를 함께 사용할 수 있다.
  $.each(contacts, function(idx,contact){
    const $tr = $('<tr>').appendTo($list);
    $('<td>').text(contact.no).appendTo($tr);
    const $td = $('<td>').appendTo($tr);
    $('<a>').attr('href','read.html?no=' + contact.no)
    .text(contact.name).appendTo($td);
    $('<td>').text(contact.address).appendTo($tr);
    $('<td>').text(contact.tel).appendTo($tr);
  });
}
const printPagination = (pagination, pageno) => {
  const $pagination = $('#pagination_div').find('.pagination');
  if(pagination.prev>0){
    const $prev = $('<li>').appendTo($pagination);
    $('<a>').attr('href', 'list.html?pageno=' + pagination.prev)
    .text('이전').appendTo($prev);
  }
  for(let i=pagination.startPage; i<=pagination.endPage; i++){
    const $li = $('<li>').appendTo($pagination);
    if(pageno==i) $li.attr('class','active');
    $('<a>').attr('href','list.html?pageno='+i).text(i)
    .appendTo($li);
  }
  if(pagination.next>0){
    const $next = $('<li>').appendTo($pagination);
    $('<a>').attr('href','list.html?pageno=' + pagination.next)
    .text('다음').appendTo($next);
  }
}

main.js

주요 코드만

$(document).ready(function(){
  // 고정된 화면영역을 조립 : composite-view 패턴
  $('#header').load('include/header.html');
  $('#nav').load('include/nav.html');
  $('#footer').load('include/footer.html');
});

read.html

주요 코드만, main.js 링크

// 주소
// read.html에 접근하는 주소 : read,html?no=번호 → 번호잘라내기
// rest 방식으로 회원정보를 요청하는 주소:
// http://sample.bmaster.kro.kr/contacts/+번호
// rest 방식으로 회원정보를 변경하는 주소:
// http://sample.bmaster.kro.kr/constacts/+번호
// 파라미터로 번호, 이름, 주소, 연락처를 보내야한다.
// rest 방식으로 프사를 변경하는 주소 : 
// http://sample.bmaster.kro.kr/constacts/+번호+/photo
// 파일 업로드를 하려면 multipart/form-data
const no = parseInt(location.search
                    .substr(location.search.indexOf('=')+1));
if(isNaN(no)==true) {
  alert('잘못된 접근입니다');
  location.href='list.html';
}
function printContact(contact){
  $('#no').text(contact.no);
  $('#name').text(contact.name);
  $('#photo').attr('src', contact.phoro);
  $('#address').val(contact.address);
  $('#tel').val(contact.tel);
}
$(document).ready(function(){
  $.ajax('http://sample.bmaster.kro.kr/contacts/'+no)
  .done(result=>printContact(result));
  
  $('#change').click(function(){
    // $는 html요소를 선택한 다음 사용하기 쉽게 양념쳤다.
    // $('아이디 선택자')[0] : jQuery로 선택한 html
    // $('#new_photo)[0] : <input type='file' id='new_photo' 
    // multiple>
    // file input 요소는 선택한 파일들을 files라고 하는 배열 속성에 저장
    // 파일을 하나만 업로드하는 경우 그 파일은 files[0]이 된다.
    // js객체를 만든 다음 $.ajax의 data 속성에 지정하면 
    // urlencoded로 자동 변경된다. (processData)
    const params = {
      no: $('#no').text(),
      name: $('#name').text(),
      address: $('#address').val(),
      tel : $('#tel').val()
    }
    // 주소와 연락처를 변경하고
    $.ajax({
      url: 'http://sample.bmaster.kro.kr/contacts/' + no,
      method: 'put',
      data: params,
      success: function(){
        // 성공하면 사진을 확인하자
        if($('#new_photo')[0].files[0]!=undefined){
          // <form enctype='multipart/form-data'>에 대한 
          // 자바스크립트 객체 생성
          const formData = new FormData();
          formData.append('photo', $('#new_photo')[0].files[0]);
          $.ajax({
            url: 'http://sample.bmaster.kro.kr/contacts/' +no
            + '/photo',
            method: 'post'
            data: formData,
            // 파일을 업로드할 때는 processData를 꺼야 한다.
            processData: false,
            // false를 주면 contentType이 multipart/form-datark ehlsek
            contentType: false,
            success: function(){
            location.reload();
          }
        });
      } else location.reload();
  })
});
$('#delete').click(function(){
  $.ajax({
    url: 'http://sample.bmaster.kro.kr/contacts/' +no,
    method: 'delete',
    success: function(){
      location.href="list.html";
    }
    ])
});
});

0개의 댓글