다연이네

[days15] Ajax 댓글 처리 본문

Spring

[days15] Ajax 댓글 처리

 다연  2021. 2. 23. 20:29
반응형

ex03_02

 

1. properties 파일 존재 여부 확인
2. ojdbc.jar 확인
3. developer

create table tbl_reply (
  rno number(10,0), 
  bno number(10,0) not null,
  reply varchar2(1000) not null,
  replyer varchar2(50) not null, 
  replyDate date default sysdate, 
  updateDate date default sysdate
);

create sequence seq_reply;

alter table tbl_reply add constraint pk_reply primary key (rno);

alter table tbl_reply  add constraint fk_reply_board  
foreign key (bno)  references  tbl_board (bno); 

 

4. ReplyVO 생성

package org.zerock.domain;

import java.util.Date;

import lombok.Data;

@Data
public class ReplyVO {

  private Long rno;
  private Long bno;

  private String reply;
  private String replyer;
  private Date replyDate;
  private Date updateDate;

}

5. ReplyMapper.java 생성

package org.zerock.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;
import org.zerock.domain.Criteria;
import org.zerock.domain.ReplyVO;

public interface ReplyMapper {

	public int insert(ReplyVO vo);

	public ReplyVO read(Long bno);

	public int delete(Long bno);

	public int update(ReplyVO reply);

	//P378 @Param 설명 	MyBatis의 @Param 기억   @Param("bno") ->#{bno}
	public List<ReplyVO> getListWithPaging(@Param("cri") Criteria cri, @Param("bno") Long bno);
	//게시글에 대한 총 댓글 수를 반환하는 메소드
	public int getCountByBno(Long bno);
}

6. ReplyMapper.xml 생성

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.zerock.mapper.ReplyMapper">

	<insert id="insert">
		insert into tbl_reply (rno, bno, reply, replyer)
		values (seq_reply.nextval, #{bno}, #{reply}, #{replyer})
	</insert>

	<select id="read" resultType="org.zerock.domain.ReplyVO">
		select *
		from tbl_reply
		where rno = #{rno}
	</select>
	
	<delete id="delete">
      delete from tbl_reply 
      where rno = #{rno}
   </delete>

   <update id="update">
      update tbl_reply 
      set reply = #{reply},updatedate = sysdate
      where rno = #{rno}
   </update>
   
   <select id="getListWithPaging"
      resultType="org.zerock.domain.ReplyVO">

     <![CDATA[
       select  rno, bno, reply, replyer, replydate, updatedate
       from 
         (
          select /*+INDEX(tbl_reply idx_reply) */ 
            rownum rn,  rno, bno, reply, replyer, replyDate, updatedate
          from tbl_reply
          where bno =  #{bno}          
             and rno > 0
             and rownum <= #{cri.pageNum} * #{cri.amount}
         ) where rn > (#{cri.pageNum} -1) * #{cri.amount}
   ]]>

   </select>


   <select id="getCountByBno" resultType="int">
      <![CDATA[
      select  count(rno) 
      from  tbl_reply 
      where  bno = #{bno}
      ]]>
   </select>
</mapper>

 

7. 단위테스트

package org.zerock.mapper;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import lombok.Setter;
import lombok.extern.log4j.Log4j;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml") 
@Log4j
public class ReplyMapperTests {
   
   @Setter(onMethod_ = @Autowired)
   private ReplyMapper mapper;

   @Test
   public void testMapper() {

      log.info(this.mapper);

   }
   
   
      
}

8. @Param 어노테이션에 대한 이해
MyBatis는 두 개 이상의 데이터를 파라미터로 전달하기 위해서는
1) 별도의 객체로 구성하거나 2)Map을 이용하거나 3) Param을 이용해 이름을 사용

 

9. ReplyService 인터페이스 생성

package org.zerock.service;

import java.util.List;

import org.zerock.domain.Criteria;
import org.zerock.domain.ReplyPageDTO;
//import org.zerock.domain.ReplyPageDTO;
import org.zerock.domain.ReplyVO;

// p.389
public interface ReplyService {

   public int register(ReplyVO vo);

   public ReplyVO get(Long rno);

   public int modify(ReplyVO vo);

   public int remove(Long rno);

   public List<ReplyVO> getList(Criteria cri, Long bno); //댓글 목록만 돌릴게 아니라
   
   // List<ReplyVO> + replyCnt = ReplyPageDTO
   public ReplyPageDTO getListPage(Criteria cri, Long bno); //댓글 수도 같이 돌리기

}


10. ReplyPageDTO 생성

package org.zerock.domain;

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;

@Data
@AllArgsConstructor
@Getter
public class ReplyPageDTO {

  private int replyCnt; //해당 게시글의 총 댓글 수 저장할 필드
  private List<ReplyVO> list;
}

11. 컨트롤러의 설계
등록 
조회
삭제
수정
페이지
컨트롤러 생성

package org.zerock.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.zerock.domain.Criteria;
import org.zerock.domain.ReplyPageDTO;
import org.zerock.domain.ReplyVO;
import org.zerock.service.ReplyService;

import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;

// p.392
@RestController //@Controller가 아니고 @RestController (jsp요청아니라 xml이나 json이나 일반 텍스트를 요청하겠다는 의미)
@RequestMapping("/replies/")
@Log4j
@AllArgsConstructor
public class ReplyController {
   private ReplyService service;

   //	 /replies/new + POST -> 댓글 등록 
   @PostMapping(value = "/new"
         , consumes = "application/json" //  json형태로 입력해서
         , produces = { MediaType.TEXT_PLAIN_VALUE }) //돌려주는 값은 일반 텍스트 문자열 (응답)
   public ResponseEntity<String> create(@RequestBody ReplyVO vo) {

      log.info("ReplyVO: " + vo);

      int insertCount = service.register(vo); //댓글 db에 저장

      log.info("Reply INSERT COUNT: " + insertCount);

      return insertCount == 1   //영향받은 레코드값
    		  	  ?  new ResponseEntity<>("success", HttpStatus.OK) //얘로 응답
                  :  new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
   }

   
   //	 /replies/41 + GET -> 댓글 조회
   @GetMapping(value = "/{rno}",  //여기 번호가 @PathVariable에 들어감
         produces = { MediaType.APPLICATION_XML_VALUE,  
               MediaType.APPLICATION_JSON_UTF8_VALUE }) //쓰고싶은대로
   public ResponseEntity<ReplyVO> get(@PathVariable("rno") Long rno) {

      log.info("get: " + rno);

      return new ResponseEntity<>(service.get(rno), HttpStatus.OK);
   }

   
   //	 /replies/41 + PUT또는PATCH -> 댓글 수정
   @RequestMapping(method = { RequestMethod.PUT, RequestMethod.PATCH }
   , value = "/{rno}"
         , consumes = "application/json" //수정하고자하는 새로입력받은 데이터는 json
         , produces = {   MediaType.TEXT_PLAIN_VALUE    }) 
   public ResponseEntity<String> modify(
         @RequestBody ReplyVO vo, 
         @PathVariable("rno") Long rno) {

      vo.setRno(rno);

      log.info("rno: " + rno);
      log.info("modify: " + vo);

      return service.modify(vo) == 1 
            ? new ResponseEntity<>("success", HttpStatus.OK)
                  : new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

   }

   //@DeleteMapping + /replies/41 		댓글 삭제 
   @DeleteMapping(value = "/{rno}", produces = { MediaType.TEXT_PLAIN_VALUE })
   public ResponseEntity<String> remove(@PathVariable("rno") Long rno) {

      log.info("remove: " + rno);

      return service.remove(rno) == 1 
            ? new ResponseEntity<>("success", HttpStatus.OK)
                  : new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);

   }

   /*
   @GetMapping(value = "/pages/{bno}/{page}", 
            produces = {
                     MediaType.APPLICATION_XML_VALUE,
                     MediaType.APPLICATION_JSON_UTF8_VALUE 
                     })
   public ResponseEntity<List<ReplyVO>> getList(
         @PathVariable("page") int page,
         @PathVariable("bno") Long bno) {


      log.info("getList.................");
      Criteria cri = new Criteria(page,10);
      log.info(cri);

      return new ResponseEntity<>(service.getList(cri, bno), HttpStatus.OK);
   }
   */

   //	 
   @GetMapping(value = "/pages/{bno}/{page}", 
            produces = { MediaType.APPLICATION_XML_VALUE,
                     MediaType.APPLICATION_JSON_UTF8_VALUE })
   public ResponseEntity<ReplyPageDTO> getList(@PathVariable("page") int page, @PathVariable("bno") Long bno) {

      Criteria cri = new Criteria(page, 10);

      log.info("get Reply List bno: " + bno);

      log.info("cri:" + cri);

      return new ResponseEntity<>(service.getListPage(cri, bno), HttpStatus.OK);
   }
    

}

12. get.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  
  <div class="panel panel-default">
   <h3>Board Read - p.251</h3>
   
         <!-- /.panel-heading -->
       <div class="panel-body">

          <div class="form-group">
          <label>Bno</label> <input class="form-control" name='bno'
            value='<c:out value="${board.bno }"/>' readonly="readonly">
        </div>

        <div class="form-group">
          <label>Title</label> <input class="form-control" name='title'
            value='<c:out value="${board.title }"/>' readonly="readonly">
        </div>

        <div class="form-group">
          <label>Text area</label>
          <textarea class="form-control" rows="3" name='content'
            readonly="readonly"><c:out value="${board.content}" /></textarea>
        </div>

        <div class="form-group">
          <label>Writer</label> <input class="form-control" name='writer'
            value='<c:out value="${board.writer }"/>' readonly="readonly">
        </div>
<%-- 
        <button data-oper='modify' class="btn btn-default">
        <a href="/board/modify?bno=<c:out value="${board.bno}"/>">Modify</a></button>
        <button data-oper='list' class="btn btn-info">
        <a href="/board/list">List</a></button>  
 --%>
 
   <button data-oper='modify' class="btn btn-default">Modify</button>
   <button data-oper='list' class="btn btn-info">List</button>
    

<%-- <form id='operForm' action="/boad/modify" method="get">
  <input type='hidden' id='bno' name='bno' value='<c:out value="${board.bno}"/>'>
</form> --%>


    <!-- p 317 -->
   <form id='operForm' action="/boad/modify" method="get">
     <input type='hidden' id='bno' name='bno' value='<c:out value="${board.bno}"/>'>
     <input type='hidden' name='pageNum' value='<c:out value="${cri.pageNum}"/>'>
     <input type='hidden' name='amount' value='<c:out value="${cri.amount}"/>'>
     
     <!-- p 345 -->
     <input type='hidden' name='keyword' value='<c:out value="${cri.keyword}"/>'>
     <input type='hidden' name='type' value='<c:out value="${cri.type}"/>'>
     
   </form> 

   </div>
   
   <!-- ------------- -->
    <div class="col-lg-12">

    <!-- /.panel -->
    <div class="panel panel-default">
<!--       <div class="panel-heading">
        <i class="fa fa-comments fa-fw"></i> Reply
      </div> -->
      
      <div class="panel-heading">
        <i class="fa fa-comments fa-fw"></i> Reply
        <button id='addReplyBtn' class='btn btn-primary btn-xs pull-right'>New Reply</button>
      </div>      
      
      
      <!-- /.panel-heading -->
      <div class="panel-body">        
      
        <ul class="chat">

        </ul>
        <!-- ./ end ul -->
      </div>
      <!-- /.panel .chat-panel -->

   <div class="panel-footer"></div>


      </div>
  </div>
  <!-- ./ end row -->
<!-- ------------- -->

<!-- p.420 ------------- -->
<!-- Modal -->
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog"
        aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal"
                aria-hidden="true">&times;</button>
              <h4 class="modal-title" id="myModalLabel">REPLY MODAL</h4>
            </div>
            <div class="modal-body">
              <div class="form-group">
                <label>Reply</label> 
                <input class="form-control" name='reply' value='New Reply!!!!'>
              </div>      
              <div class="form-group">
                <label>Replyer</label> 
                <input class="form-control" name='replyer' value='replyer'>
              </div>
              <div class="form-group">
                <label>Reply Date</label> 
                <input class="form-control" name='replyDate' value='2018-01-01 13:13'>
              </div>
      
            </div>
<div class="modal-footer">
        <button id='modalModBtn' type="button" class="btn btn-warning">Modify</button>
        <button id='modalRemoveBtn' type="button" class="btn btn-danger">Remove</button>
        <button id='modalRegisterBtn' type="button" class="btn btn-primary">Register</button>
        <button id='modalCloseBtn' type="button" class="btn btn-default">Close</button>
      </div>          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <!-- /.modal -->
<!-- ------------- -->      
    
<!-- p 265 --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
  $(document).ready(function (){
     var operForm = $("#operForm");
     
     $("button[data-oper='modify']").on("click", function (e){
        operForm.attr("action","/board/modify").submit();
     });
     
     // http://localhost/board/list?[pageNum=3&amount=5 ]
     $("button[data-oper='list']").on("click", function (e){
        operForm.find("#bno").remove();
        operForm.attr("action","/board/list").submit();
     }); 
  });
</script>
<script src="/resources/js/reply.js"></script>
<script>
   // 1.
   // console.log( replyService );
   
   // 2.
   /* 
   console.log("----------");
   console.log("JS TEST");
   var bnoValue = '<c:out value="${board.bno}"/>';
   replyService.add({ reply:"JS TEST", replyer:"tester", bno:bnoValue }
                    ,function (result){
                       alert("RESULT: " + result);
                    });
    */
    
    // 3. p 407
    /* 
    console.log("----------");
    console.log("JS TEST");
    var bnoValue = '<c:out value="${board.bno}"/>';
    replyService.getList({ bno:bnoValue, page:1 }
                     ,function (list){
                        for (var i = 0, len=list.length||0 ; i < len; i++) {                           
                           console.log(list[i]);
                   }
                     });
     */
</script>

<script>
// p.415
$(document).ready(function () {
  //조회하는 게시글 번호
  var bnoValue = '<c:out value="${board.bno}"/>';
  
  var replyUL = $(".chat"); //댓글을 표시하기 위한 ul태그
  //alert( bnoValue );
  //alert( replyUL );
    showList(1);
    
function showList(page){
   
     console.log("show list " + page);
    
    replyService.getList({bno:bnoValue,page: page|| 1 }, function(replyCnt, list) {
      
    console.log("replyCnt: "+ replyCnt );
    console.log("list: " + list);
    console.log(list);
    
    if(page == -1){
      pageNum = Math.ceil(replyCnt/10.0);
      showList(pageNum);
      return;
    }
      
     var str="";
     
     if(list == null || list.length == 0){
       return;
     }
     
     for (var i = 0, len = list.length || 0; i < len; i++) {
       str +="<li class='left clearfix' data-rno='"+list[i].rno+"'>";
       str +="  <div><div class='header'><strong class='primary-font'>["
          +list[i].rno+"] "+list[i].replyer+"</strong>"; 
       str +="    <small class='pull-right text-muted'>"
           +replyService.displayTime(list[i].replyDate)+"</small></div>";
       str +="    <p>"+list[i].reply+"</p></div></li>";
     }
     
     replyUL.html(str);
     
     showReplyPage(replyCnt);

 
   });//end function
     
 }//end showList
    
    var pageNum = 1;
    var replyPageFooter = $(".panel-footer");
    
    function showReplyPage(replyCnt){
      
      var endNum = Math.ceil(pageNum / 10.0) * 10;  
      var startNum = endNum - 9; 
      
      var prev = startNum != 1;
      var next = false;
      
      if(endNum * 10 >= replyCnt){
        endNum = Math.ceil(replyCnt/10.0);
      }
      
      if(endNum * 10 < replyCnt){
        next = true;
      }
      
      var str = "<ul class='pagination pull-right'>";
      
      if(prev){
        str+= "<li class='page-item'><a class='page-link' href='"+(startNum -1)+"'>Previous</a></li>";
      }
      
      for(var i = startNum ; i <= endNum; i++){
        
        var active = pageNum == i? "active":"";
        
        str+= "<li class='page-item "+active+" '><a class='page-link' href='"+i+"'>"+i+"</a></li>";
      }
      
      if(next){
        str+= "<li class='page-item'><a class='page-link' href='"+(endNum + 1)+"'>Next</a></li>";
      }
      
      str += "</ul></div>";
      
      console.log(str);
      
      replyPageFooter.html(str);
    }
     
    replyPageFooter.on("click","li a", function(e){
       e.preventDefault();
       console.log("page click");
       
       var targetPageNum = $(this).attr("href");
       
       console.log("targetPageNum: " + targetPageNum);
       
       pageNum = targetPageNum;
       
       showList(pageNum);
     });     

    
/*     function showList(page){
      
      replyService.getList({bno:bnoValue,page: page|| 1 }, function(list) {
        
        var str="";
       if(list == null || list.length == 0){
        
        replyUL.html("");
        
        return;
      }
       for (var i = 0, len = list.length || 0; i < len; i++) {
           str +="<li class='left clearfix' data-rno='"+list[i].rno+"'>";
           str +="  <div><div class='header'><strong class='primary-font'>"+list[i].replyer+"</strong>"; 
           str +="    <small class='pull-right text-muted'>"+replyService.displayTime(list[i].replyDate)+"</small></div>";
           str +="    <p>"+list[i].reply+"</p></div></li>";
         }


    replyUL.html(str);

      });//end function
      
   }//end showList */
   
    var modal = $(".modal");
    var modalInputReply = modal.find("input[name='reply']");
    var modalInputReplyer = modal.find("input[name='replyer']");
    var modalInputReplyDate = modal.find("input[name='replyDate']");
    
    var modalModBtn = $("#modalModBtn");
    var modalRemoveBtn = $("#modalRemoveBtn");
    var modalRegisterBtn = $("#modalRegisterBtn");
    
    $("#modalCloseBtn").on("click", function(e){
       
       modal.modal('hide');
    });
    
    $("#addReplyBtn").on("click", function(e){
      
      modal.find("input").val("");
      modalInputReplyDate.closest("div").hide();
      modal.find("button[id !='modalCloseBtn']").hide();
      
      modalRegisterBtn.show();
      
      $(".modal").modal("show");
      
    });
    

    modalRegisterBtn.on("click",function(e){
      
      var reply = { //json이 아니라 js Object, 
            reply: modalInputReply.val(),
            replyer:modalInputReplyer.val(),
            bno:bnoValue
          }; //js Object -> json 변환하고자 한다면 ? JSON.stringify(reply)
      replyService.add(reply, function(result){
        
        alert(result); //success 
        
        //modal.find("input").val(""); 모달창 초기화
        //modal.modal("hide");			숨기기
        
        //showList(1);
        showList(-1); //함수 가보면 -1이면 댓글 목록 다시 출력하는 코딩
        
      });
      
    });


  //댓글 조회 클릭 이벤트 처리 
    $(".chat").on("click", "li", function(e){
      
      var rno = $(this).data("rno");
      
      replyService.get(rno, function(reply){
      
        modalInputReply.val(reply.reply);
        modalInputReplyer.val(reply.replyer);
        modalInputReplyDate.val(replyService.displayTime( reply.replyDate))
        .attr("readonly","readonly");
        modal.data("rno", reply.rno);
        
        modal.find("button[id !='modalCloseBtn']").hide();
        modalModBtn.show();
        modalRemoveBtn.show();
        
        $(".modal").modal("show");
            
      });
    });
  
    
/*     modalModBtn.on("click", function(e){
      
      var reply = {rno:modal.data("rno"), reply: modalInputReply.val()};
      
      replyService.update(reply, function(result){
            
        alert(result);
        modal.modal("hide");
        showList(1);
        
      });
      
    });

    modalRemoveBtn.on("click", function (e){
         
       var rno = modal.data("rno");
       
       replyService.remove(rno, function(result){
             
           alert(result);
           modal.modal("hide");
           showList(1);
           
       });
       
     }); */

    modalModBtn.on("click", function(e){
         
        var reply = {rno:modal.data("rno"), reply: modalInputReply.val()};
        
        replyService.update(reply, function(result){
              
          alert(result);
          modal.modal("hide");
          showList(pageNum);
          
        });
        
      });


      modalRemoveBtn.on("click", function (e){
        
        var rno = modal.data("rno");
        
        replyService.remove(rno, function(result){
              
            alert(result);
            modal.modal("hide");
            showList(pageNum);
            
        });
        
      });

 
});

</script>



<script>

/* console.log("===============");
console.log("JS TEST");

var bnoValue = '<c:out value="${board.bno}"/>'; */

//for replyService add test
/* replyService.add(
    
    {reply:"JS Test", replyer:"tester", bno:bnoValue}
    ,
    function(result){ 
      alert("RESULT: " + result);
    }
); */


//reply List Test
/* replyService.getList({bno:bnoValue, page:1}, function(list){
    
     for(var i = 0,  len = list.length||0; i < len; i++ ){
       console.log(list[i]);
     }
});
 */

 
/*  //17번 댓글 삭제 테스트 
 replyService.remove(17, function(count) {

   console.log(count);

   if (count === "success") {
     alert("REMOVED");
   }
 }, function(err) {
   alert('ERROR...');
 });
 */
 

//12번 댓글 수정 
/* replyService.update({
  rno : 12,
  bno : bnoValue,
  reply : "Modified Reply...."
}, function(result) {

  alert("수정 완료...");

});  
 */

</script>  

</body>
</html>

13. reply.js

console.log("Reply Module........");

/*
// p.401
var replyService = (function() {
                  return { name : "AAAA" };                  
               })();
*/

/*
// p.402
var replyService = (function() {
                  function add(reply, callback){
                      console.log("reply.....");
                  }
                  return { add : add };                  
               })();
*/

 
var replyService = (function() {

   function add(reply, callback, error) {
      console.log("add reply...............");

      $.ajax({
         type : 'post',
         url : '/replies/new',
         data : JSON.stringify(reply), //stringify : 위 reply(문자열)를 json타입으로 변환할 때 사용
         contentType : "application/json; charset=utf-8",
         success : function(result, status, xhr) {
            if (callback) {
               callback(result);
            }
         },
         error : function(xhr, status, er) {
            if (error) {
               error(er);
            }
         }
      })
   }

//   function getList(param, callback, error) {
//
//      var bno = param.bno;
//      var page = param.page || 1;
//

 //        /replies/pages/41/2
//      $.getJSON("/replies/pages/" + bno + "/" + page + ".json",
//            function(data) {
//               if (callback) {
//                  callback(data);
//               }
//            }).fail(function(xhr, status, err) {
//         if (error) {
//            error();
//         }
//      });
//   }
   
   

   function getList(param, callback, error) {

       var bno = param.bno;
       var page = param.page || 1;
       
       $.getJSON("/replies/pages/" + bno + "/" + page + ".json",
           function(data) {
          
             if (callback) {
               //callback(data); // 댓글 목록만 가져오는 경우 
               callback(data.replyCnt, data.list); //댓글 숫자와 목록을 가져오는 경우 
             }
           }).fail(function(xhr, status, err) {
         if (error) {
           error();
         }
       });
     }

   
   function remove(rno, callback, error) {
      $.ajax({
         type : 'delete',
         url : '/replies/' + rno,
         success : function(deleteResult, status, xhr) {
            if (callback) {
               callback(deleteResult);
            }
         },
         error : function(xhr, status, er) {
            if (error) {
               error(er);
            }
         }
      });
   }

   function update(reply, callback, error) {

      console.log("RNO: " + reply.rno);

      $.ajax({
         type : 'put',
         url : '/replies/' + reply.rno,
         data : JSON.stringify(reply),
         contentType : "application/json; charset=utf-8",
         success : function(result, status, xhr) {
            if (callback) {
               callback(result);
            }
         },
         error : function(xhr, status, er) {
            if (error) {
               error(er);
            }
         }
      });
   }

   function get(rno, callback, error) {

      $.get("/replies/" + rno + ".json", function(result) {

         if (callback) {
            callback(result);
         }

      }).fail(function(xhr, status, err) {
         if (error) {
            error();
         }
      });
   }

   function displayTime(timeValue) {

      var today = new Date();

      var gap = today.getTime() - timeValue;

      var dateObj = new Date(timeValue);
      var str = "";

      if (gap < (1000 * 60 * 60 * 24)) {

         var hh = dateObj.getHours();
         var mi = dateObj.getMinutes();
         var ss = dateObj.getSeconds();

         return [ (hh > 9 ? '' : '0') + hh, ':', (mi > 9 ? '' : '0') + mi,
               ':', (ss > 9 ? '' : '0') + ss ].join('');

      } else {
         var yy = dateObj.getFullYear();
         var mm = dateObj.getMonth() + 1; // getMonth() is zero-based
         var dd = dateObj.getDate();

         return [ yy, '/', (mm > 9 ? '' : '0') + mm, '/',
               (dd > 9 ? '' : '0') + dd ].join('');
      }
   }
   ;

   return {
      add : add,
      get : get,
      getList : getList,
      remove : remove,
      update : update,
      displayTime : displayTime
   };

})();
 
반응형
Comments