ajax 학습 2. 댓글 등록 ajax로 구현, 댓글 비동기 처리

HMS·2022년 10월 5일
0

댓글 등록/삭제 ajax로 구현해보기

javascript

//댓글 등록
$("#rSubmit").click(function(){
			console.log("${board.boardNo}");
			var replyContents = $("#replyContents").val();
			var refBoardNo = "${board.boardNo}";
			$.ajax({
				url : "/board/replyAdd.kh",
				type : "post",
				data : {
					"refBoardNo" : refBoardNo,
					"replyContents" : replyContents
					}, // key값 : 넘기는값 ctrl shift - 하면 칸나누기가능
				async: true,
				success : function(result){
					if(result == "success"){
						alert("댓글등록 성공!");
						$("#replyContents").val(""); //작성 후 내용 초기화
						getReplyList();
// 						location.href="/board/detail.kh?boardNo="+ ${board.boardNo} +"&page=" + ${page};
						//dom조작 함수호출등 가능
					}else if(result == "noneId"){
						alert("로그인 하세여");
						location.href="/home.kh";
					}else{
						alert("댓글등록 실패!");
					}
				},
				error : function(){
					console.log("등록실패");
				}
				
				
				
			})
		});
//댓글 삭제
function removeReply(replyNo){
			if(confirm("댓글을 삭제하시겠습니까?")){
			$.ajax({
				url : "/board/replyRemove.kh",
				type : "post",
				data : {"replyNo" : replyNo},
				success : function(result){
					
					if(result>0){
					alert("삭제 성공");
					console.log("삭제 성공");
					getReplyList();
					}else{
						alert("삭제 실패");
					}
				},
				error : function(){
					console.log("서버요청 실패")
				}
			})
			}
		}

controller

//댓글 등록
	@ResponseBody
	@RequestMapping(value = "/board/replyAdd.kh" , method = RequestMethod.POST)
	public String boardReplyAdd(
			@ModelAttribute Reply reply
			,@RequestParam(value = "page" , required = false) Integer page
			,HttpSession session) {
		Member member = (Member) session.getAttribute("loginUser");
		if(session.getAttribute("loginUser") == null) {
			return "noneId";
		}
		String reWriter = member.getMemberId();
		reply.setReplyWriter(reWriter);
		int result = bService.registerReply(reply);
		if(result > 0) {
			return "success";
			//html의 body부분에 이 값을 보내겠다 responsebody
		}else {
			return "fail";
		}
//댓글 삭제
	@ResponseBody
	@RequestMapping(value = "/board/replyRemove.kh" , method = RequestMethod.POST)
	public Integer replyRemove(
			@RequestParam("replyNo") Integer replyNo
			,HttpSession session) {
		Integer result = bService.removeReply(replyNo);
		return result;
	}
  1. form 형태를 제거 하고 ajax형태로 js를 구성한다.
  2. 댓글 내용은 textarea의 id값 value를 받아 key값으로 넘겨주고 댓글을 달아줄 게시글번호는 el을 사용하여 key 값으로 설정한 후 controller로 넘겨준다 해당값들은 domain 변수들과 같은이름으로 지정해주어 modelattribute로 받아준다
  3. session에서 로그인된 아이디를 get한 후 reply 클래스에 set해준다
  4. reply를 서비스단에 넘겨주어 mapper를 실행한다
  5. $("#replyContents").val(""); 으로 작성 후 내용 초기화 시켜준다
  6. getReplyList();함수(아래에서 만들어준)를 호출해 비동기 처리를 해준다.
  7. 삭제의 경우 replylist에서 replyNo를function으로 받아서 controller로 보낸준 후 삭제 mapper실행해 주면 된다.
    a태그의경우 href="javascript:void(0);"을 사용하면 눌리지 않는다
  8. @ResponseBody를 적어주지 않으면 오류가 나니 항상 주의

댓글 비동기 처리를 위한 함수 만들기

javascript

<script>
getReplyList();
function getReplyList(){
			var boardNo = "${board.boardNo}";
		$.ajax({
			
			url : "/board/replyList.kh",
			type : "get",
			data : {"boardNo" : boardNo}, //보드넘버넘김
			success : function(rList){
				var $tableBody = $("#rtb tbody")
				$tableBody.html(""); // 댓글등록시 초기화 해주는 함수 안해주면 append로 쌓임
				$("#rCount").text("댓글(" + rList.length + ")");
				var str = "";
				if(rList != null){
					
					/* for(var i = 0; i<rList.length ; i++){ */
					for(var i in rList){
						str += "<tr><td width='100'>" + rList[i].replyWriter +  "</td>"
						str += "<td>" +  rList[i].replyContents +  "</td>"
						str += "<td>" +  rList[i].rUpdateDate +  "</td>"
						str += "<td><a href='#'>수정</a> <a href='javascript:void(0);' onclick='removeReply("+rList[i].replyNo +")'>삭제</a></td></tr>"
					}
					
						$("#rtb").html(str);
				}				
			},
			error : function(){
				console.log("서버요청 실패!")
			}			
		});
		}

controller

@ResponseBody
	@RequestMapping(value = "/board/replyList.kh" , produces = "application/json;charset=utf-8" , method = RequestMethod.GET)
	public String boardReplyList(
			@RequestParam("boardNo") Integer boardNo
			,ModelAndView mv) {
		int bNo = (boardNo == 0 ) ? 1:boardNo;
		List<Reply> rList = bService.printAllReply(bNo);
		mv.addObject("rList",rList);
		if(!rList.isEmpty()) {
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
			return gson.toJson(rList);
		}
		
		
		return null;
	}
  1. js변수 boardNo로 지정 값은 el값으로 받아준다
  2. boardNo를 controller에서 param값으로 받는다
  3. 해당 데이터를 gson.toJson(rList)으로 gson화 해서 넘겨준다
  4. var str에 +=로 html과 data들을 차곡차곡 쌓아서 $("#rtb").html(str); 으로 출력한다
  5. append를 사용해서 html코드를 쌓았으면 등록시 중복적용됨으로 $tableBody.html("");를 중간에 넣어주어 중복적용을 방지한다.
profile
안녕하세요

0개의 댓글