• Home
  • About
    • Young's Github Pages photo

      一日不作一日不食

    • About
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

JavaScript 정리 09

15 Feb 2019

Reading time ~5 minutes

JavaScript 정리 09 - 페이지 이동(2), popup


페이지 이동

01

  • input태그 submit타입은 유효성 검증 없이 바로 값들을 서버로 전송
    • JS 값 검증을 실행 후 값이 유효하지 않아도 전송을 해버림
    • 따라서 input submit타입은 사용하지 않도록 한다.
  • input태그 button타입일 경우 버튼을 눌러도 서버로 값이 전송되지 않는다.
    • JS로 유효성에 대한 검증가능
    • 검증 후 location.href, location.replace(), document.폼이름.submit()로 페이지 이동
// 페이지의 이동만 수행
location.href = "url";
location.replcae("url");

// 값을 가지고 페이지 이동
document.form이름.submit();
<body>
<form action="request.jsp" method="get" name="frm">
      <label>이름</label>
      <input type="text" name="name" id="name" class="inputBox"/><br/>
      <label>나이</label>
      <input type="text" name="age" id="age" class="inputBox"/><br/>
      <input type="button" value="버튼 전송" class="btn"  onclick="useSubmit()"/><br/>
      <!-- submit은 JS의 유효성 검증 결과에 상관없이 BackEnd로 전송한다. -->
      <input type="submit" value="submit 전송" class="btn"  onclick="useSubmit()"/><br/>
</form>
</body>
<script type="text/javascript">
     useSubmit = () => {
          
          var obj = document.frm;
          
          if(obj.name.value.replace(/ /g,"") == "") {
               obj.name.value="";
               obj.name.focus();
               alert('이름은 필수 입력입니다.');
               return;
          }
          
          if(obj.age.value.replace(/ /g, "") == "") {
               obj.age.value="";
               obj.age.focus();
               alert('나이는 필수 입력입니다.');
               returnl
          }
          
          alert('서버(BackEnd) 전송합니다');

          // 단순 페이지 이동 : 값은 이동하지 않고 페이지 이동만 한다.
          // location.href="request.jsp";
          // location.replace("request.jsp");
          
          // document.폼이름.submit() :
          // form태그가 감싸고 있는 모든 HTML Form Control의 값을  가지고 페이지 이동한다.
          obj.submit();
     }
</script>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
서버에서 제공(응답)하는 페이지<br/>
입력하신 정보입니다.<br/>
이름 : <%= request.getParameter("name") %><br/>
나이 : <%= request.getParameter("age") %>살<br/>
<a href="form_submit.html">뒤로이동</a>
</body>
</html>

02

03

페이지 이동 - history

  • 브라우저에 남아있는 페이지 이동정보
    • 브라우저의 뒤 또는 앞 버튼을 가지고 이동가능
    • 브라우저가 종료되면 다 사라진다.
  • 서버로부터 응답을 받을 때마다 history가 추가된다.
    • 서버로 요청을 보내지 않고 이전 응답기록(history)으로 이동한다.
  • 히스토리 개수
history.length
  • 뒤로(이전) 이동
    • 이동하는 이전 페이지에 HTML Form Control이 존재한다면 사용자가 입력한 모든 값이 그대로 보여진다
    • password만 초기화 된다.
history.back()
  • 앞으로 이동
history.go(이동할 히스토리 수) // +면 앞으로, -면 뒤로 이동
  • 예) browser 열면 history 상태는 0
    • daum.net에 들어가면 history가 1이됨
    • naver.com으로 또 이동, history가 2가 됨
    • google.com으로 또 이동, history가 3이됨
    • nate.com으로 또 이동, history가 4가됨
    • history.back()쓰면 google로 이동
    • history.back()쓰면 naver로 이동
    • history.back()쓰면 daum으로 이동
    • history.go(1)쓰면 naver로 이동
    • history.go(1)쓰면 google로 이동
    • history.go(1)쓰면 nate로 이동
    • history.go(-2)쓰면 naver로 이동
<body>
      <input type="button" value="히스토리의 수" onclick="historyCnt()">
      <input type="button" value="뒤로" onclick="historyBack()">
      <input type="button" value="앞으로" onclick="historyGo()">
</body>
<script type="text/javascript">
      historyCnt = () => {
            alert(history.length);
      }
      
      historyBack = () => {
            history.back();
            // history.go(-1); // 뒤로 한번 이동
      }
      
      historyGo = () => {
            history.go(1);
      }
</script>

04

<!-- 서버에게 요청하여 페이지를 이동 : 입력값이 모두 사라진다. -->
<a href="form_submit.html">뒤로이동</a>
<!-- history 사용하여 페이지 이동 : 입력값이 유지된다. -->
<a href="javascript:history.back()">history다시 입력</a>

05

  • 뒤로 이동을 클릭하면 초기화됨(서버에 새로 요청한 응답을 받으므로)
  • history다시 입력을 클릭한 경우 history.back()이 호출됨, 이전으로 이동
    • form의 정보가 남아있다.
    • password필드의 정보만 초기화된다.

06

창 닫기

  • popup인 경우 그냥 닫고 window인 경우 confrim dialog로 닫기 여부를 묻는다.
window.self.close()

이동할 url 없는경우

  • #void를 입력해서 이동을 막는다.

popup

  • 부가적인 정보를 제공할 때 사용하는 창
    • 우편번호찾기가 대표적인 예
  • popup은 window.onload로 많이 띄운다.
  • 속성은 n개가 들어갈 수 있다.
    • "”로 묶여있어야 된다.
      • 속성값에 ““를 쓰지 않는다.
// popup 세번째 파라미터, 속성들
"width=창의 넓이"
"height=창의 높이"
"top=y좌표"
"left=x좌표"
window.open("팝업창에들어갈HTML","창id","속성");
  • popup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
      window.onload = () => {
            window.open("newyear_popup.html","newYear","width=500,height=565,top=200,left=500");
      }
</script>
</head>
<body>
접속자에게 서비스 할 내용...
<img src="images/Ryan.gif"/>
</body>
</html>
  • child.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
      #popupWrap {
            margin:0px auto;
            width:450px;
            height: 550px;
      }
      
      #popupContainer {
            width:460px;
            height:520px;
      }
      
      #popupFooter {
            width:460px;
            height:30px;
      }
</style>
<script type="text/javascript">
      function winClose() {
            // 팝업창 닫기 : popup인 경우 그냥 닫히고,
            // window인 경우 confrim dialog로 닫기 여부를 묻는다.
            self.close();
      }
      
</script>
</head>
<body>
<div id="popupWrap">
      <div id="popupContainer">
            <img src="images/newyear_2019.jpg" alt="img"/>
      </div>
      <div id="popupFooter">
            <input type="checkbox" name="closeFlag"/>오늘 하루 이 창을  열지 않음
            <a href="#void" onclick="winClose()">닫기</a>
      </div>
</div>
</body>
</html>

07

윈도우의 현재 좌표 얻기

  • 부모창의 윈도우 좌표를 구해 popup창의 위치를 지정해주면 항상 브라우저 내에서 popup이 뜬다.
window.screenX
window.screenY
<script type="text/javascript">
      window.onload = () => {
            window.open("newyear_popup.html","idNewYear","width=500,height=565,top="+(window.screenY+100)+",left="+(window.screenX+100));
      }
</script>

08

자식창(popup)에서 부모창으로 값 전달

09

  • 부모창(자식창을 띄워준 창)
    • opener 사용
opener.window.document.폼이름.value = "부모창에 전달할 값";
  • parents.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css"  href="../common/css/main_v20190130.css">
<script type="text/javascript">
     window.onload = function() {
          document.getElementById("btnDup").addEventListener("click",popupCenter);
     }
     
     function popupCenter() {
          window.open("child.html","idDup","width=522,height=323,top="
                    +(window.screenY+200)+",left="+(window.screenX+400));
     }
</script>
</head>
<body>
<form name="pFrm">
     <input type="text" name="id" id="id" placeholder="아이디"  readonly="readonly" class="inputBox"/>
     <input type="button" value="중복확인" class="btn" id="btnDup"/>
</form>
</body>
</html>
  • child.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
     #idWrap {
          width: 502px;
          height:303px;
          background: #FFFFFF url(images/id_background.png) no-repeat;
          margin:0px auto;
          position: relative;
     }
     
     #idContainer {
          position: absolute;
          top: 110px;
          left:80px;
     }
</style>
<script type="text/javascript">
     window.onload = () => {
          document.getElementById("sendId").addEventListener("click",sendOpener);

          //  keyup하면 submit되버림
          document.getElementById("id").addEventListener("keydown",keyCheck); 
     }
     
     function keyCheck() { // 엔터가 눌렸을 때 sendOpener호출(submit막음)
          if(window.event.which == 13) {
               sendOpener();
          }           
     }
     
     function sendOpener() {
          
          // 1. 자식창에서 전송할 값 받기
          var idObj = document.cFrm.id;
          
          if (idObj.value.trim() == "") {
               alert("전송할 id를 입력해주세요.");
               idObj.focus();
               return;
          }
          
          // 2. 부모창으로 값 넘기기
          opener.window.document.pFrm.id.value = idObj.value.trim();
          
          // 3. 자식창 닫기
          self.close();
     }
</script>
</head>
<body>
<div id="idWrap">
     <div id="idContainer">
          <form name="cFrm">
               <label>아이디</label>
               <input type="text" id="id" name="id" class="inputBox"  autofocus="autofocus"/>
               <input type="button" value="사용" class="btn"  id="sendId"/>
          </form>
     </div>
</div>
</body>
</html>

10

11

부모창에서 자식창으로 값 전달

  • ie에서만 동작, 크롬에서는 안된다.
// 1. 자식창 받기
var 변수명 = window.open("자식창.html","창id","속성");

// 2. 자식창 값 전달
변수명.window.document.form명.name.value = 전달할값;
  • parent.html
<body>
<form name="pFrm">
      <input type="text" name="pid" id="pid" placeholder="아이디"  class="inputBox"/>
      <input type="button" value="값전송 중복확인" class="btn"  id="btnSendDup"/>
</form>
</body>
<script type="text/javascript">
      window.onload = function() {
            document.getElementById("btnSendDup").addEventListener("click",popupCenterSend);
      }
       
      function popupCenterSend() {
            // 자식창을 띄울 때 부모창에 있는 값을 전달하여 띄우기
            var id = document.pFrm.pid.value;

            // 1. 자식창을 변수에 저장
            var subWin =  window.open("child.html","idDup","width=522,height=323,top="
                        +(window.screenY+200)+",left="+(window.screenX+400));
            // 2. 부모창의 값을 자식창으로 전달
            var id = document.pFrm.pid.value;
            
            // 3. 자식창으로 값 전달
            subWin.window.document.cFrm.id.value = id;
      }
</script>
  • child.html은 위 예제코드와 동일

12



JavaScript