2020.11.14 HTML PPT 10 정리 BOM 과 DOM JAVASCRIPT 공부 location 객체

 location 객체 




1) location 객체를 이용해서 현재페이지의 정보를 읽어오기 


<script>

 function proc1() {


res = "href=" + location.href + "<br>"; 

res += "protocol : " + location.protocol + "<br>";

res += "host : " + location.host + "<br>"; 

res += "hostname : " + location.hostname + "<br>"; 

res += "port : " + location.port + "<br>";


    document.getElementById('result1').innerHTML = res; 

</script>


<body>

    <input type="button" value="확인" onclick="proc1()"> 

    <div id="result1"> 

</body>



2) jsp 페이지를 만들어서 페이지를 변경하게 해줄것


<script>

 function proc2() {

    location.href='test.jsp'; 

}

 function goPage() {

    location.href='test.jsp?code=2&name=홍길동'; 

}

function replaceProc(){

    location.replace('test.jsp');

    //페이지를 새로열지 않고 원래있던 페이지에서 교체. 뒤로가기 안됨 ...


}

function reloadProc() {

    str = ["Hello~~" , "JavaScript" , "HTML" , "CSS" , "jQuery" , "Good~"]; 

    rand = Math.floor(Math.random() * str.length) ;

    res = "<h1>" + str[rand] + "</h1>"; 

 

  //버튼누르면 reloadProc 가 호출되고 str 중에 1개가 빨간글씨로 출력된다.    

    document.getElementById('result2').innerHTML = res; 

    document.getElementById('result2').style.color = 'red'; 

  

    // 1초 후에 현재문서를 다시 보여준다. 

    setTimeout(function() { location.reload();  } , 1000 ) ; 

    

}


</script>




<body>

    <input type="button" value="페이지이동" onclick="proc2()">

    <a href="javascript:goPage()">공지사항목록</a>

    //"javascript:goPage()" 얘는 지금여기있는 함수 호출 ( 링크대신) 

    <button type="button" onclick="location.href=`test.jsp?code=1&name=korea`">공지사항목록</button> //이렇게 바로 가게 할 수도 있다. 위에 javascript:goPage() 는 함수호출을 해서 한번 과정을 더 거치는 것 


    <button type="button" onclick="replaceProc()">공지사항 목록 </button>

    <button type="button" onclick="reloadProc()">페이지 재호출</button>


</body>



//test.jsp 페이지



<script>

function gogo() {

    history.go(-2) // 전페이지는 -1 전전페이지는 -2 ...

}

</script> 


<body> 

 <h1>JSP : Java Server Page</h1>

클라이언트에서 페이지 요청시 데이타를 받아서 서버내에서 실행하는 서버프로그램이다. <br>

<%

    //?code=2&name=홍길동 이부분이 위에서 온것. 

   //만약 위에 두개가 인자로 오지 않으면, 위에 기본바디에 있는애만 출력 ( proc 2 ) 

    String scode = request.getParameter("code"); 

    String sname = request.getParameter("name"); 


    if ( scode != null && scode.equals("1") ) {

        // scode 가 값이 보내는 경우와 안보내는 경우가 있는데 안보내는 경우에는 scode는             null 이다. 그래서 scode 가 null 이 아닌지를 먼저 검사해야 한다. 

        // scode.equals("1") && scode != null 이렇게 순서를 바꾸면 밑에있는 out.print 출력                안됨. 

        out.print(" <p> 이름 : " + sname + "</p>" ) ; 

     }


%>


<a href="#" onclick="gogo()">뒤로</a>


</body>





- 참고 : a 태그에서는 location.href 는 사용할 수 없다. 


    











댓글