본문 바로가기
공부/Trouble Shooting

자바스크립트에서 자바 함수 호출

by son_i 2023. 9. 6.
728x90
<%
	String x = request.getParameter("xvalue");
	String y = request.getParameter("yvalue");
	System.out.println(x);

%>
<div>
		LAT: <input type="text" id="x" value="0.0">, 
		LNT: <input type="text" id="y" value="0.0">
		<button id="my-Space" onclick="calDist_()">내 위치 가져오기</button>
		<script>
		<% double xx = 0; double yy = 0; %>
    		function calDist_() {
    			var x = document.getElementById('x').value;
			var y = document.getElementById('y').value;
			<%=xx %> = x;
			<%=yy %> = y;
	  		<% apiService.calDist(xx, yy); %>
    		}
  		</script>
		<input type="button" value="근처 WIPI 정보 보기">
		
	</div>

input 태그에서 입력한 좌표 값을 받아서 자바스크립트로 변수에 저장하고

이 값으로 만들어놓은 자바 함수를 호출하고 싶은데 이 상태로 실행하니까 

값 입력도 하지 않고 버튼도 누르지 않았는데 서버는 계속 로딩되고 자바 함수가 먼저 호출이 되어서 db에 마구 값이 저장되어버림. . 

 

알고보니 JSP는 자바코드 -> dom -> 자바 스크립트 순으로 실행이 되어서 그냥 초기값 0, 0으로 잔뜩 계산이 되어버린다.

음으음음

 


9/6 새로운 방법을 찾아냈다.

자바스크립트문으로 input type에 지정된 값을 얻어낸다음에 새로운 jsp를 호출해서 그 값들을 넘겨주기 !

<div>
		LAT: <input type="text" id="x" value="0.0">, 
		LNT: <input type="text" id="y" value="0.0">
		<button id="my-Space" onclick="calDist_()">내 위치 가져오기</button>
		<script>
    		function calDist_() {
    			var x = document.getElementById('x').value;
			var y = document.getElementById('y').value;
			location.href='distUpdate.jsp?xvalue=x&yvalue=y';
    		}
  		</script>
		<input type="button" value="근처 WIPI 정보 보기">
		
	</div>

이렇게 만들고

 

<distUpdate.jsp>에

<%
	double x = Double.parseDouble(request.getParemeter("xvalue"));
	double y = Double.parseDouble(request.getParameter("yvalue"));
	System.out.println(x+" "+y);

%>

이렇게 작성했더니

오류발생

1. 값을 넘겨주는 형식이 잘못됐거나

2. 받을 때 잘못 받았거나 !

이 오류만 해결하면 어떻게 될 것 같다

 

음 ㅋㅋ <distUpdate.jsp> 11행에 오타가 났다. getParameter 로 수정 !

java.lang.NumberFormatException: For input string: "x"

이런 오류 발생

-> 숫자가 아닌 타입을 숫자로 변환할 때 생기는 에러

 

<%
	String x = request.getParameter("xvalue");
	String y = request.getParameter("yvalue");
	System.out.println(x);

%>

이렇게 바꿔줬는데 x랑 y가 출력이 됨.

자바스크립트에서 주소값에 값을 넘겨줄때 잘못 된 듯 !

 

function calDist_() {
    			var x = document.getElementById('x').value;
			var y = document.getElementById('y').value;
			location.href='distUpdate.jsp?xvalue='+x+'&yvalue='+y;
    		}

이렇게 하니까 됐다 !

자바스크립트 변수값을 넘겨줄 땐 + 기호로 연결 !!!

 - 여기 도움을 정말 많이 받았따 ㅠㅠㅜㅠ

https://codeong.tistory.com/160

 

[JSP] 파라미터를 넘겨 받는 방법 - getParameter()/getParameterValues()/getParameterMap

getParameter() 과 getParameterValues를 주로 사용한다. getParameterMap() 리턴 타입이 Map이다. 클라이언트(웹브라우저) 에서 서버로 파라미터 넘기기 1. GET 방식 [방법1] a 태그 이용 내용 [방법2] 버튼으로 전

codeong.tistory.com


 

728x90