yahayaha

22. ajax 댓글 처리 본문

spring/프로젝트

22. ajax 댓글 처리

yaha 2024. 2. 9. 22:20

먼저 JSP 내에서 스크립트 처리를 하기에는 복잡해지기에 모듈화를 실행.

 

webapp 내 resource 폴데어 reply.js 파일 작성.

 

 console.log("Reply Module...");
 
 var replyservice = {};

 

reply.js 파일은 게시물 조회 페이지에 사용하려고 작성. get.jsp에 스크립트 추가.

 

<script type="text/javascript" src="/resources/js/reply.js"></script>
                            
<script type="text/javascript">
    $(document).ready(function(){
        var operForm = $("#operForm");

        $("button[data-oper='modify']").on("click", function(){
            operForm.attr("action","/board/modify").submit();
        });
    });
</script>

 

reply.js가 정상적으로 동작 되는지 f12 개발자 도구에서 network에서 확인.

 

 

모듈 구성

모듈 패턴은 Java의 클래스처럼 JavaScript를 이용해서 메서드를 가지는 객체를 구성.

 

모듈 패턴은 JavaScript의 즉시 실행함수와 '{}'를 이용해서 객체를 구성.

 

 console.log("Reply Module...");
 
 var replyservice = (function(){
 
 	return {name:"AAAA"};
 	
 });

 

JavaScript의 즉시 실행함수는 () 안에 함수를 선언하고 바깥쪽에서 실행.

즉시 실행함수는 함수의 실행 결과가 바깥쪽에서 선언된 변수에 할당.

 

replyService라는 변수에 name이라는 속성에 'AAAA'라는 속성값을 가진 객체가 할당됨.

 

console.log에서 확인 해보기위해 get.jsp 수정.

 

<script type="text/javascript">
    $(document).ready(function(){
        var operForm = $("#operForm");

        console.log(replyService);

        $("button[data-oper='modify']").on("click", function(){
            operForm.attr("action","/board/modify").submit();
        });
    });
</script>

 

ajax 등록 처리

모듈 패턴은 즉시 실행하는 함수 내부에서 필요한 메서드를 구성해서 객체를 구성하는 방식. 

 

console.log("Reply Module...");
 
 var replyService = (function(){
 
 	function add(reply, callback){
 		console.log("Reply...."); 	
 	}
    
 	return {add:add};
 	
 })();

 

이 코드를 개발자 도구에서는 replyService 객체의 내부에서 add라는 메서드가 존재하는 형태로 보이게됨.

외부에서 replyService.add(객체, 콜백)를 전달하는 형태로 호출 

ajax 호출은 감춰져 있기 때문에 코드를 더욱 깔끔하게 작성 가능.

 

reply.js에 add함수는 ajax를 이용해서 POST 방식으로 호출하는 코드 작성.

 

console.log("Reply Module...");
 
 var replyService = (function(){

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

    $.ajax({
        type : 'post',
        url : '/replies/new',
        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);
            }
        }
    });
}
return {add:add};

 })();

 

add()에서 데이터 전송 타입이 'applica-utf-8' 방식으로 전송한다는 점과 파라미터로 callback과 error를 함수로 받을 것이라는걸 인식해야함.

 

만일 ajax 호출이 성공하고, callback 값으로 적절한 함수가 존재한다면 해당 함수를 호출해서 결과를 반영.

 

get.jsp를 수정해서 replyService.add()를 호출.

 

 console.log("==========");
    console.log("JS 테스트");

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

    replyService.add(
        {reply:"JS 테스트", replyer:"테스터", bno:bnoValue},
        function(result){
            alert("RESULT : " + result);
        }
    );

 

데이터베이스에도 정상적으로 추가 확인.

 

댓글 목록 처리

이제 해당 게시물에 있는 댓글 전체 목록을 처리 해경해야함.

 

댓글 목록은 최종적으로 페이징 처리가 되어야 하지만, 일단 전체 댓글을 가져오는걸 우선적으로 처리.

 

먼저 ' /replies/pages/게시물번호/페이지번호.xml' 또는  ' /replies/pages/게시물번호/페이지번호.json '

 

형태로 데이터를 먼저 확인 가능.

 

replt.js에서는 ajax 호출을 담당. jQuery의 getJSON()을 이용해서 처리.

 

 var replyService = (function(){
 
 //등록
 	function add(reply, callback){
 		console.log("Reply....");
 		
 		$.ajax({
			type : 'post',
			url : '/replies/new',
			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 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);
 				}
 			}).fail(function(xhr, status, err){
 			if(error){
 			error();
 			} 			
 		});
 	}
 	return {
 		add:add,
 		getList : getList
 		};
 })();

getList()는 param이라는 객체를 통해서 파라미터를 전달받아 JSON 목록을 호출 

JSON 형태가 필요하므로 URL 호출 시 확장자를 .json으로 요구.

 

get.jsp에 댓글 리스트를 가져오는지 확인. 

 

 

댓글 삭제와 업데이트

 var replyService = (function(){
 
 //등록
 	function add(reply, callback){
 		console.log("Reply....");
 		
 		$.ajax({
			type : 'post',
			url : '/replies/new',
			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 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);
 				}
 			}).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);
                        }
                    }
                });
                }
 	return {
 		add:add,
 		getList : getList,
        remove : remove
 		};
 })();

 

remove()는 delete 방식으로 데이터를 전달. $ajax()를 이용해서 구체적으로 type 속성 delete를 지정.

get.jsp에서 실제 데이터베이스에 있는 댓글 번호를 이용해서 삭제되는지 확인.

 

<script type="text/javascript">

    console.log("==========");
    console.log("JS 테스트");

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

    /* replyService.add(
        {reply:"JS 테스트", replyer:"테스터", bno:bnoValue}
        ,
        function(result){
            alert("RESULT : " + result);
        } 

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

    // 댓글 삭제
    replyService.remove(17, function(count){

        console.log(count);

        if(count === "success"){
            alert("삭제완료");
        }
    }, function(err){
        alert("에러...");
    });
</script>

데이터베이스에도 rno 17 댓글이 삭제된걸 확인

 

바로 댓글 수정(업데이트) 처리까지 진행.

 

댓글 수정같은 경우 댓글의 번호까지 전송 해야함. 댓글 내용은 JSON 형태로 전송하기에 댓글 등록이랑 유사한 부분이 많음.

 

 var replyService = (function(){
 
 //등록
 	function add(reply, callback){
 		console.log("Reply....");
 		
 		$.ajax({
			type : 'post',
			url : '/replies/new',
			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 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);
 				}
 			}).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);
                }
            }
        });
    }
 	return {
 		add:add,
 		getList : getList,
        remove : remove,
        update : update
 		};
 })();
<script type="text/javascript">

    console.log("==========");
    console.log("JS 테스트");

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

    /* replyService.add(
        {reply:"JS 테스트", replyer:"테스터", bno:bnoValue}
        ,
        function(result){
            alert("RESULT : " + result);
        } 

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

    // 댓글 삭제
    replyService.remove(17, function(count){

        console.log(count);

        if(count === "success"){
            alert("삭제완료");
        }
    }, function(err){
        alert("에러...");
    });
    
    // 댓글 수정
    replyService.update({
        rno : 16,
        bno : bnoValue,
        reply : "댓글 수정 테스트...."
    }, function(result){
        alert("수정 완료...")
    });
</script>

 

댓글 조회 처리

특정 번호 댓글 조회는 GET 방식으로 동작.

 

 var replyService = (function(){
 
 //등록
 	function add(reply, callback){
 		console.log("Reply....");
 		
 		$.ajax({
			type : 'post',
			url : '/replies/new',
			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 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);
 				}
 			}).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();
            }
        });
    }
 	return {
 		add:add,
 		getList : getList,
        remove : remove,
        update : update,
        get : get
 		};
 })();

 

get.jsp에서는 단순 댓글번호만 전달.

 

<script type="text/javascript">

    console.log("==========");
    console.log("JS 테스트");

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

    /* replyService.add(
        {reply:"JS 테스트", replyer:"테스터", bno:bnoValue}
        ,
        function(result){
            alert("RESULT : " + result);
        } 

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

    // 댓글 삭제
    replyService.remove(17, function(count){

        console.log(count);

        if(count === "success"){
            alert("삭제완료");
        }
    }, function(err){
        alert("에러...");
    });
    
    // 댓글 수정
    replyService.update({
        rno : 16,
        bno : bnoValue,
        reply : "댓글 수정 테스트...."
    }, function(result){
        alert("수정 완료...")
    });
    
    // 댓글 조회
    replyService.get(16, function(data){
    	console.log(data);
    });
</script>

.

 

이 과정이 끝났으면 ajax 처리는 완료된 것을 확인. 이제 이벤트 처리와 HTML 처리만하면 끝.

'spring > 프로젝트' 카테고리의 다른 글

24. 댓글 페이징처리.  (0) 2024.02.12
23. 댓글 기능( 이벤트 , view 처리)  (2) 2024.02.11
21. 댓글 처리하기 (Controller 처리)  (0) 2024.02.08
20. 댓글 처리하기 (CRUD)  (1) 2024.02.05
19. 검색처리 (JSP수정)  (0) 2024.02.04