본문 바로가기
  • Welcome J-Kyu Tstory
PROJECT/보드게임프로젝트

[BGMaster]_Ajax를 활용한 데이터 Controller로 보내기

by regularity 2022. 7. 27.
728x90

1. Ajax 기능 사용 배경

▶싱글게임(updown)에서 버튼을 누를때마다 카운트 증가, 게임 시작과 동시에 게임 기록을 위한 타이머 기능을 추가
▶카운트 값과 타이머 값을 JSP에서 Controller로 보내는 과정에서 적용

2. 처음 시도 방법

#문제점 발생
<Script>에서 HTML의 <div>태그로 값을 받을 경우 웹 브라우저에 값이 정상 적으로 뜨지만 form태그로 감싸서 submit으로 제출할 경우 Controller에 값이 전달되지 않는 문제 발생
(<input>태그로 받을 경우 웹 브라우저에 값이 전달 되지 않음)

 

3. Ajax 기능을 이용한 데이터 전송 방법

(1) HTML코드

 <form id="record_form" name="record_form" method="post"> 
	    <!-- 총 시도 횟 수를 script의 변수의 값을 넣을 태그 -->
		<div id="try_count" class="try_count" name="recordCount"></div>
			
		<!-- 타이머 기록을 담을 태그 -->
		<h1>
			<div id="stopwatch" class="recordTime" name="recordTime" style="margin: 100px" value="">
			        00:00:00
		    </div>
	    </h1>
		<br>	
		
    	<input type="button" style="display:none" id="record_btn" class="record_btn" value="기록저장" onclick="submit_record()">
	</form>

 

(2) 스크립트 카운팅 알고리즘

var total_count=0;	//시도 횟수를 저장할 전역변수

	function makeRanNum(){
		startClock();	//스탑워치 실행
		randomNum = (parseInt)(Math.random()*1 +1);
		total_count = 0;	//시작과 동시에 시도횟수 전역변수를 0으로 초기화
		document.querySelector("#try_count").innerText=total_count;
	}
	
	function answer_check() {
		console.log("answer_check() 작동");
		this.total_count+=1;	
		console.log(total_count);
		document.querySelector("#try_count").innerText=total_count;
		if($("#inputNum").val() < randomNum){alert("UP!");$("#inputNum").focus(); return false;}
		if($("#inputNum").val() > randomNum){alert("DOWN!");$("#inputNum").focus(); return false;}
		if($("#inputNum").val() == randomNum){
			stopClock();	//정답을 맞출 시 타이머 정지
			$("#record_btn").show();  // show
			alert("정답입니다!");
			console.log("this.total_count"+total_count);
		}

(3) 스크립트 타이머 알고리즘

<!-- ==============================================스크립트_타이머 알고리즘============================================ -->
	<script type="text/javascript">
	let timerId;  --->타이머를 저장할 변수
	let time = 0;
	const stopwatch = document.getElementById("stopwatch");
	let  hour, min, sec;

		
		function printTime() {
		    time++;
		    stopwatch.innerText = getTimeFormatString();
		}
		
		//시계 시작 - 재귀호출로 반복실행
		function startClock() {
		    printTime();
		   	stopClock();
		    timerId = setTimeout(startClock, 1000);
		}
		
		//시계 중지
		function stopClock() {
		    if (timerId != null) {
		        clearTimeout(timerId);
		    }
		}
		
		// 시계 초기화
		function resetClock() {
		    stopClock()
		    stopwatch.innerText = "00:00:00";
		    time = 0;
		}
		
		// 시간(int)을 시, 분, 초 문자열로 변환
		function getTimeFormatString() {
		    hour = parseInt(String(time / (60 * 60)));
		    min = parseInt(String((time - (hour * 60 * 60)) / 60));
		    sec = time % 60;
		
		    return String(hour).padStart(2, '0') + ":" + String(min).padStart(2, '0') + ":" + String(sec).padStart(2, '0');
		}
	</script>

 

(4) Ajax 코드

function submit_record(){
		console.log("제출 버튼 실행");
		console.log("제출 total_count 실행------->"+total_count);
		console.log("제출 버튼 timerId실행------>" +timerId);

		$.ajax({
			url : "/game/updown", //전송할 url
			type : "post", //전송할 메서드 타입
			dataType : "text", //받을 데이터 타입 안정하면 기본 xml형식
			data : {"recordCount" : total_count,"recordTime" : timerId}, //전송할 데이터 
			success : function(a){
				
			}
		});

	}

 

(5) Controller의 POST메서드

	//----------------updown게임_POST -----------------------
	@ResponseBody
	@PostMapping(value="/updown")
	public String postUpdown(RecodeDTO recodeDTO/*, @RequestParam(name ="recordCount") String a, @RequestParam(name ="recordTime") String b */) throws Exception{
		
		logger.info("updown게임_POST 진입");
		//logger.info("a:{}",a);
		//logger.info("b:{}",b);
		logger.info("recordTime:{}",recodeDTO.getRecordTime());
		logger.info("recordCount:{}",recodeDTO.getRecordCount());
		
		return "";
	}

 

728x90

'PROJECT > 보드게임프로젝트' 카테고리의 다른 글

[BGMaster]_프로젝트 구조  (0) 2022.07.26

댓글