getJSON() 안될때, 값이 안들어올때

서현서현·2022년 7월 19일
0

작은 실수들

목록 보기
9/19
post-thumbnail

진짜 열받네

	<!-- 댓글과 관련된 html 소스 -->
	<div class="row">
		<div class="col-md-12">
		
			<!-- 댓글 입력부  -->
			<div class="box box-success">
				<div class="box-header">
					<h3 class="box-title">ADD NEW REPLY</h3>
				</div>
				<div class="box-body">
					<label for="exampleInputEmail1">Writer</label><input
					class="form-control" type="text" placeholder="USER ID"
					id="newReplyWriter"><label for="exampleInputEmail1">Reply
					Text</label> <input class="form-control" type="text"
					placeholder="REPLY TEXT" id="newReplyText">
				</div>
				<!-- /.box-body -->
				
				<!-- 댓글입력폼 제출부 -->
				<div class="box-footer">
					<button type="submit" class="btn btn-primary" id="replyAddBtn">ADD 
					REPLY</button>
				</div>
			</div>		
			
			<!-- The time line : 댓글목록 -->
			<ul class="timeline">
				<!-- timeline time label -->
				<li class="time-label" id="repliesDiv">
					<span class="bg-green">
						Replies List 
					</span>
				</li>
			</ul>
			
			<div class="text-center">
				<ul id="pagination" class="pagination pagination-sm no-margin">
				
				</ul>
			</div>
			
		</div>
	</div>

요런 html이 있다. 뭐냐면 그냥... 댓글 입력하는 부분, 그걸 제출하는 부분, 그리고 달려있는 댓글목록을 보는 부분이다. 실행하면 다음과같다.

근데이제 해야할일은 Replies List 영역에 댓글목록도 불러와서 띄워놔야하고, 새댓글 작성시에 add reply 버튼을 누르면 새로 등록이 되도록 해야함

그래서 JS처리를 하는데... replies list를 띄울때 코드가 너무 반복되고 그러면 귀찮으니까 템플릿을 사용함. handlebars 라는걸 사용!

<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>

<!-- 템플릿 : 댓글리스트(타임라인) 출력  -->
<script id="template" type="text/x-handlebars-template">
{{#each .}}
<li class="replyLi" data-rno={{rno}}>
<i class="fa fa-comments bg-blue"></i>
 <div class="timeline-item" >
  <span class="time">
    <i class="fa fa-clock-o"></i>{{prettifyDate regdate}}
  </span>
  <h3 class="timeline-header"><strong>{{rno}}</strong> -{{replyer}}</h3>
  <div class="timeline-body">{{replytext}} </div>
    <div class="timeline-footer">
     <a class="btn btn-primary btn-xs" 
	    data-toggle="modal" data-target="#modifyModal">Modify</a>
    </div>
  </div>			
</li>
{{/each}}
</script>

템플릿은 위와같이 작성... 부트스트랩이 붙어있어 다소 가독성이 떨어지지만... 혀튼 리플넘버인 rno와 등록날짜(regdate), 댓글내용을 띄운다. each를 통해 주어진 갯수만큼 반복한다..

	Handlebars.registerHelper("prettifyDate", function(timeValue) {
		var dateObj = new Date(timeValue);
		var year = dateObj.getFullYear();
		var month = dateObj.getMonth() + 1;
		var date = dateObj.getDate();
		return year + "/" + month + "/" + date;
	});
		
	var printData = function(replyArr, target, templateObject) {

		var template = Handlebars.compile(templateObject.html());

		var html = template(replyArr);
		$(".replyLi").remove();
		target.after(html);

	}

그리고.. 사실 뭔지 잘 모르겠지만.... date를 원한느 형식으로 띄워주기위해 handlebars에서 일종의 함수역할(?)인 helper를 사용해서 선언해주고, 컴파일해서 replyLi의 기존내용 삭제후 넣어준다.

	var bno = ${boardVO.bno};
	
	var replyPage = 1;

	function getPage(pageInfo){
		
		$.getJSON(pageInfo,function(data){
			printData(data.list, $("#repliesDiv") ,$('#template'));
			printPaging(data.pageMaker, $(".pagination"));
			
		});
	}

그리고 댓글도 페이징처리는 필요하니까 getPage를 만들어서 해당 페이지에 대한 값을 JSON형식으로 읽어오고, printData(아까 위에있던거)와 printPaging을 실행. 전자는 JSON 데이터의 리스트를 템플릿형식으로 변환해 #repliesDiv에 붙이는거고 후자는 JSON데이터의 pageMaker 결과를 .pagination에 갖다붙임.


	var printPaging = function(pageMaker, target) {

		var str = "";

		if (pageMaker.prev) {
			str += "<li><a href='" + (pageMaker.startPage - 1)
					+ "'> << </a></li>";
		}

		for (var i = pageMaker.startPage, len = pageMaker.endPage; i <= len; i++) {
			var strClass = pageMaker.cri.page == i ? 'class=active' : '';
			str += "<li "+strClass+"><a href='"+i+"'>" + i + "</a></li>";
		}

		if (pageMaker.next) {
			str += "<li><a href='" + (pageMaker.endPage + 1)
					+ "'> >> </a></li>";
		}

		target.html(str);
	};
	

printPaging은 페이지바 만들어서 갖다붙임.

	$("#repliesDiv").on("click", function() {

		if ($(".timeline li").size() > 1) {
			return;
		}
		getPage("/replies/" + bno + "/1");

	});
	

	$(".pagination").on("click", "li a", function(event){
		
		event.preventDefault();
		
		replyPage = $(this).attr("href");
		
		getPage("/replies/"+bno+"/"+replyPage);
		
	});

repliesDiv를 클릭했을때 타임라인이 1개보다 많으면, 즉 이미 로드되어 있으면 그냥 리턴(종료)하고 로드되어있지 않음녀 1페이지를 getPage()한다.
pagination의 li요소를 클릭하면 그 요소에 포함되어있는 링크가 발동된다.

근데 왜 id="repliesDiv" 클릭이 안될까.... alert로 직어봤다

	function getPage(pageInfo){
			alert("test");
		$.getJSON(pageInfo,function(data){
			alert("0");
			printData(data.list, $("#repliesDiv") ,$('#template'));
			alert("1");
			printPaging(data.pageMaker, $(".pagination"));
			alert("2");
		});
	}

test만 alert 표시되고 012는 아예 안뜸,... 즉 $.getJSON이 작동안하고있다. 컨트롤러까진 가지나?

	@RequestMapping(value="/{bno}/{page}", method=RequestMethod.GET)
	public ResponseEntity<Map<String,Object>> listPage(
			@PathVariable("bno") Integer bno,
			@PathVariable("page") Integer page) {
		System.out.println("마 테스트 함 할게!!!!!!!!!!!!!!!!!!!!!!!");
		System.out.println(bno);
		System.out.println(page);


엥 잘 들어...오는군요?

리턴도 잘된다...

$.getJSON(pageInfo,function(data){
  console.log(data.length);

근데 왜.... 길이가 안뜰까..... 왜 리턴값이 처리가 안되나요........이러지마세요


간단한 JSON예제도 실행해봤는데 이거 조차도 DB의 객체는 컨트롤러에서 가져오는데 getJSON 함수가 발동을 안했다.....

그래서 결국 질문 올렸는데 해답을 찾아주심

ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ쿠키님 당신은 최고의 선생님입니다

워낙 구판이라 그냥 혼자 해결해야겠다 하고있었는데 친절히 힌트를 주셨다... 눈물쥬륵

결론 : 라이브러리 추가를 안했음

ㅋㅋ
JSON 테스트 하는 프로젝트를 따로 파서 하다보니.....
dependency를 거기에만 추가하고 여기엔 안한것이다.....
바보아님?
이거땜에 이틀동안 삽질 엄청했네

		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.4</version>
		</dependency>

jackson을 추가해준다.

다시 실행하니까 놀라울정도로 잘돌아감 ㅎㅎ;

그래도 개고생한덕에 코드는 좀 이해한듯

삽질끝ㅋㅋ

0개의 댓글