반응형

1. Ajax란?

 

  • 비 동기식 방식으로 웹서버의 응답을 기다리지 않고 데이터를 빠르게 처리하는 개발 기법
  • 기존 방식은 웹서버의 응답으로 페이지의 깜빡임(새로고침)이 있고 난 뒤 데이터가 처리 됐지만 Ajax는 페이지 리로딩 없이 데이터를 처리
  • 대표적 기능으로 네이버나 구글의 실시간 검색이나 검색어 자동완성 등이 있습니다.

 

단점 

  • 페이지의 리로딩이 없기 때문에 한페이지에서 지속적으로 사용시 리소스가 계속 쌓여 페이지가 느려짐
  • 스크립트로 되어 있기 때문에 에러 발생 시 디버깅에 어려움이 있습니다.

 

2. 예제

 

우선 Ajax를 사용하기 위해서는 jquery가 필요합니다. 다음과 같이 jquery 에서 직접 제공하는 주소를 사용하거나 js파일을 구하셔서 import 해야 합니다.

 

 

화면단


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<script src="http://code.jquery.com/jquery-1.7.js" type="text/javascript"></script>
 
<html>
<head>
    <title>Home</title>
     
    <script type="text/javascript">
     
    function AjaxEx(){
         
        var name = "name="+document.check.name.value;
             
        $.ajax({
            url : "/check",
            type : "post",
            data : name,
            dataType : "json",
            success : function(data) {
                 
                document.getElementById("result").innerHTML = data+"님 반갑습니다.";
                     
                },
                 
            error : function(request) {
             
                alert("실패");
             
                 
            }
        });
 
        }
     
    </script>
</head>



1
2
3
4
5
6
7
8
9
10
11
<body>
 
<h3>Ajax 예제 입니다..</h3>
<form action="" name="check" method="post">
<input type="text" id="name">
<input type="button" value="클릭" onclick="AjaxEx()">
<div id="result"></div>
</form>
 
</body>
</html>



JAVA단


1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RequestMapping(value = "/check", method = RequestMethod.POST)
    public void check(HttpServletRequest request, HttpServletResponse resp) throws Exception {
                 
        String name = request.getParameter("name");
         
        JSONObject obj = new JSONObject();
        JSONArray ja = new JSONArray();
         
        ja.add(name);
         
        PrintWriter out = resp.getWriter();
        out.print(ja.toString());
             
    }



스프링 기본 기본 프로젝트를 생성하신 후 실행 시키면 나오는 Home 화면에 다음과 같이 JSP단을 작성해 줍니다.

그리고 텍스트박스에 이름을 넣으시고 클릭 버튼을 누르면 스크립트 펑션을 타고 Ajax를 수행하고 결과를 리턴해 줍니다.

 

또한 Ajax특성상 컨트롤러(JAVA단)을 거쳐오고도 페이지 리로딩 없이 결과를 화면에 뿌려줍니다.

반응형
반응형

.slideDown( [duration] [, callback] )Returns : jQuery


개요 : 슬라이딩을 해서 요소를 보이게 합니다.


 slideDown( duration [, callback] )

  • duration 시간 값
  • callback 콜백 함수
  • .slideDown( [duration] [, easing] [, callback] )
  • duration 시간 값
  • easing 특수한 효과 함수
  • callback 콜백 함수

  • .slideDown() 함수는 요소의 height 값을 조작해서 움직임을 만들어 냅니다. 시간값(Duration)의 기본값은 밀리세컨드이고, 값이 크면 느린 효과가 나타납니다. 물론 반대는 빨라지겠죠. 'fast' 와 'slow' 문자열을 지원하는데, 각각은 200 과 600 밀리세컨드를 의미합니다.

    이미지를 예로 보겠습니다.


     <div id="clickme">
      Click here
    </div>
    <img id="book" src="book.png" alt="" width="100" height="123" />


     $('#clickme').click(function() {
      $('#book').slideDown('slow', function() {
        // Animation complete.
      });
    });


    시작과 끝 효과 ( Easing )

    .animate() 인자 중에 남은 하나는 속도 늦추는 함수(easing function)에 대한 내용입니다. 이 easing 함수는 속도에 대한 내용입니다. 움직임이 한쪽 끝에 닿았을때 처리되는 행동패턴에 대한 내용입니다. jQuery에서 easing 은 기본으로 swing 을 사용합니다. swing은 끝점에 가서 속도가 살짝 느려집니다. 또 하나는 속도를 그대로 유지하는 linear 입니다. easing 함수들을 정상적으로 사용하려면 plug-ins 들이 필요합니다. 대부분 jQuery UI suite 쪽에 정의되어 있습니다.

    콜백 함수 ( Callback Function )

    애니메이션이 완료된 후 사용될 콜백함수입니다. 이 콜백함수는 인자를 전달할 수 없지만, this 를 이용하여 애니메이션이 일어난 요소 자체를 전달할 수는 있습니다. 만일 여러개의 요소에 움직임 효과를 주었다면 각각의 애니메이션 효과가 일어난 뒤에 개별적으로 콜백함수가 실행이 됩니다.


    jQuery 1.6 버전부터는deferred.done() 와 함께 .promise() 함수를 사용하여 모든 움직임이 끝난 후 한번만 콜백함수를 실행할 수 있게 되었습니다. ( .promise() 함수 예제 링크 ).

    .slideDown() 을 포함하여 모든 jQuery effect 들은, 글로벌 세팅인 jQuery.fx.off = true로 조절할 수 있습니다. 더 많은 정보를 원하시면 jQuery.fx.off를 참고하십시오.


    예 제  

    모든 div를 슬라이드 다운합니다.


     <!DOCTYPE html>
    <html>
    <head>
      <style>
    div { background:#de9a44; margin:3px; width:80px; 
    height:40px; display:none; float:left; }
    </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
      Click me!
    <div></div>
    <div></div>
    <div></div>
    <script>
    $(document.body).click(function () {
    if ($("div:first").is(":hidden")) {
    $("div").slideDown("slow");
    } else {
    $("div").hide();
    }
    });

    </script>

    </body>
    </html>



    미리보기

    <iframe src="http://cfs.tistory.com/custom/blog/68/684698/skin/images/09.14.01.html" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="width: 100%; height: 180px;"></iframe>

    스르륵 내려옵니다.



    예 제  
    모든 input 을 슬라이드 다운합니다. 움직임이 완료되면 가운데 input 요소에 포커스를 줍니다.


     <!DOCTYPE html>
    <html>
    <head>
      <style>
    div { background:#cfd; margin:3px; width:50px; 
    text-align:center; float:left; cursor:pointer;
    border:2px outset black; font-weight:bolder; }
    input { display:none; width:120px; float:left; 
    margin:10px; }
    </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
      <div>Push!</div>
    <input type="text" />
    <input type="text" class="middle" />

    <input type="text" />
    <script>
    $("div").click(function () {
    $(this).css({ borderStyle:"inset", cursor:"wait" });
    $("input").slideDown(1000,function(){
    $(this).css("border", "2px red inset")
    .filter(".middle")
    .css("background", "yellow")
    .focus();
    $("div").css("visibility", "hidden");
    });
    });

    </script>

    </body>
    </html>



    미리보기

    <iframe style=" marginwidth=">0" marginheight="0" frameborder="0" scrolling="no" src="http://cfs.tistory.com/custom/blog/68/684698/skin/images/09.14.02.html" px="px">

    스르륵 내려온 뒤 포커스가 갑니다. 왠지 유용해 보입니다.

     

    슬라이드 기능은 기존 웹에서는 거의 구현하지 못하는 기능이었습니다. 이제는 함수 하나로 되는 세상이네요. 매번 얘기하지만 jQuery 감사~~.

    그럼 즐프하세요.



    ※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.





    반응형
    반응형

    .slideUp( [duration] [, callback] )



    개요 : 슬라이드를 이용해 요소를 숨깁니다.


     

  • .slideUp( duration [, callback] )
  • duration 시간 값
  • callback 콜백 함수
  • .slideUp( [duration] [, easing] [, callback] )
  • duration 시간 값
  • easing 특수한 효과 함수
  • callback 콜백 함수

  • .slideUp() 함수는 요소의 height 값을 조작해서 움직임을 만들어 냅니다. 보이게 처리할 때 display 속성값을 jQuery 의 데이터 캐쉬에 저장 해두었다가 나중에 display 를 초기값으로 복원해줍니다. 만일 요소의 display 스타일 속성값이 inline 이었다면, display 속성값이 inline 으로 복원된다는 의미입니다.

    시간값(Duration)의 기본값은 밀리세컨드이고, 값이 크면 느린 효과가 나타납니다. 물론 반대는 빨라지겠죠. 'fast' 와 'slow' 문자열을 지원하는데, 각각은 200 과 600 밀리세컨드를 의미합니다.

    이미지를 예로 보겠습니다.


     <div id="clickme">
      Click here
    </div>
    <img id="book" src="book.png" alt="" width="100" height="123" />


     $('#clickme').click(function() {
      $('#book').slideUp('slow', function() {
        // Animation complete.
      });
    });



    시작과 끝 효과 ( Easing )

    .animate() 인자 중에 남은 하나는 속도 늦추는 함수(easing function)에 대한 내용입니다. 이 easing 함수는 속도에 대한 내용입니다. 움직임이 한쪽 끝에 닿았을때 처리되는 행동패턴에 대한 내용입니다. jQuery에서 easing 은 기본으로 swing 을 사용합니다. swing은 끝점에 가서 속도가 살짝 느려집니다. 또 하나는 속도를 그대로 유지하는 linear 입니다. easing 함수들을 정상적으로 사용하려면 plug-ins 들이 필요합니다. 대부분 jQuery UI suite 쪽에 정의되어 있습니다.

    콜백 함수 ( Callback Function )

    애니메이션이 완료된 후 사용될 콜백함수입니다. 이 콜백함수는 인자를 전달할 수 없지만, this 를 이용하여 애니메이션이 일어난 요소 자체를 전달할 수는 있습니다. 만일 여러개의 요소에 움직임 효과를 주었다면 각각의 애니메이션 효과가 일어난 뒤에 개별적으로 콜백함수가 실행이 됩니다.


    jQuery 1.6 버전부터는deferred.done() 와 함께 .promise() 함수를 사용하여 모든 움직임이 끝난 후 한번만 콜백함수를 실행할 수 있게 되었습니다. ( .promise() 함수 예제 링크 ).

    .slideUp() 을 포함하여 모든 jQuery effect 들은, 글로벌 세팅인 jQuery.fx.off = true로 조절할 수 있습니다. 더 많은 정보를 원하시면 jQuery.fx.off를 참고하십시오.


    예 제  

    모든 div 태그를 슬라이드 업 합니다.


     <!DOCTYPE html>
    <html>
    <head>
      <style>
      div { background:#3d9a44; margin:3px; width:80px; 
        height:40px; float:left; }
      </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
      Click me!
      <div></div>
      <div></div>
      <div></div>
      <div></div>

      <div></div>
    <script>
      $(document.body).click(function () {
        if ($("div:first").is(":hidden")) {
          $("div").show("slow");
        } else {
          $("div").slideUp();
        }
      });

      </script>

    </body>
    </html>



    미리보기

    <iframe src="http://cfs.tistory.com/custom/blog/68/684698/skin/images/09.16.01.html" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="width: 100%; height: 180px;"></iframe>

    슬라이드 업 되면서 사라집니다.

     

    예 제  
    부모 p 태그를 슬라이드 업하고 완료되면 메시지 처리를 합니다.


     <!DOCTYPE html>
    <html>
    <head>
      <style>
    div { margin:2px; }
    </style>
      <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
      <div>
      <button>Hide One</button>
      <input type="text" value="One" />

    </div>
    <div>
      <button>Hide Two</button>
      <input type="text" value="Two" />

    </div>
    <div>
      <button>Hide Three</button>
      <input type="text" value="Three" />

    </div>
    <div id="msg"></div>
    <script>
      $("button").click(function () {
        $(this).parent().slideUp("slow", function () {
          $("#msg").text($("button", this).text() + " has completed.");
        });
      });

    </script>

    </body>
    </html>



    미리보기


    <iframe src="http://cfs.tistory.com/custom/blog/68/684698/skin/images/09.16.02.html" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="width: 100%; height: 180px;"></iframe>

    콜백 함수 사용이 핵심이네요.




    ※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.

    반응형
    반응형

    현재 페이지에서 팝업의 기능이 있을 경우 새창으로 띄우는 형태의 모달창으로 하지않고

    레이어 형태의 팝업으로 새로고침이 되지않는게 특징이다.

    아래의 화면처럼 리스트의 상세보기 버튼이 있다고 가정하고 

    구현된 소스를 보면 이해가 쉬울것같다.

    참고로 소스는 스프링 기반 타임리프라는 라이브러리의 소스이다.


    타임리프thymeleaf란?

    자바 라이브러리이며, 웹과 웹이 아닌 환경 양쪽에서 텍스트, HTML, XML, Javascript, CSS 그리고 텍스트를 생성할 수 있는 템플릿 엔진이다. 웹 애플리케이션에서 뷰View 계층 에 보다 적합하지만, 오프라인 환경에서 많은 형태로 처리가 가능하다.

    스프링 MVC와의 통합 모듈을 제공하며, 애플리케이션에서 JSP로 만든 기능들을 완전히 대체할 수 있다.

    타임리프의 목표는 세련되고 잘다듬어진 템플릿을 제공하는 것이다. Standard SpringStandard를 통해서 강력하고 자연스러운 테플릿을 만들어낼 수 있어 정적 프로토타입도 브라우저에서 정확하게 동작한다. 거기서 더 나아가 다이얼렉트dialect를 개발하여 타임리프를 확장할 수 있다. 




    <!-- board_top -->

    <div class="board_top">

     <div class="lside">

      <h3>배포오류현황</h3>

     </div>

    </div>

    <!-- //board_top -->

    <!-- board_list -->

    <div class="board_list01">

     <table summary="">

     <caption>배포오류현황 : 목록</caption>

     <colgroup>

      <col width="110" />

      <col width="*" />

      <col width="142" />

      <col width="142" />

      <col width="142" />

      <col width="142" />

      <col width="142" />

     </colgroup>

     <thead>

     <tr>

      <th scope="col" class="first"><em>오류횟수</em></th>

      <th scope="col"><em>오류구분</em></th>

      <th scope="col"><em>배포시도일</em></th>

      <th scope="col"><em>배포담당자</em></th>

      <th scope="col"><em>긴급여부</em></th>

      <th scope="col"><em>첨부파일</em></th>

      <th scope="col"><em>상세정보</em></th>

     </tr>

     </thead>

     <tbody>

     <tr th:each="dItem: ${distList}">

      <td class="first">

       <div th:text="${dItem.distSeqNo != null} ? ${dItem.distSeqNo} : ''" class="article"></div>

      </td>

      <td>

       <div th:text="${dItem.distResultCode != null} ? ${T(com.skt.msdp.common.CommonCodeHelper).getName('MODTYPE', dItem.distResultCode)} : ''" class="article"></div>

      </td>

      <td>

       <div th:text="${dItem.distTryDate != null} ? ${#dates.format(dItem.distTryDate, 'yyyy-MM-dd')} : ''"  class="article">2013-00-00</div>

      </td>

      <td>

       <div class="article">

        <!-- tooltipbox -->

        <span class="tooltipbox">

         <em th:text="${dItem.distEmpName != null} ? ${dItem.distEmpName} : ''" empno="" th:attr="empno=${dItem.distEmpNo}"></em>

        </span>

        <!-- //tooltipbox --> 

       </div>

      </td>

      <td>

       <div th:text="${dItem.urgencyYn != '' and dItem.urgencyYn == 'Y'} ? 'Yes' : 'No'" class="article">No</div>

      </td>

      <td>

       <div th:switch="${dItem.map.get('fileRelId') != null} ? ${true} : ${false}" class="article" >   

        <span th:case="${true}">

           <a th:href="'/fileRel/download?fileRelId='+${dItem.map.get('fileRelId')}" class="btn_white30"><span>다운로드</span></a></span>

        <span th:case="${false}"></span>

       </div>

      </td>

      <td>

       <div th:switch="${dItem.modDetailDesc != null} ? ${true} : ${false}" class="article">

        <span th:case="${true}"><a th:href="'javascript:fnPopupView('+${dItem.distSeq}+');'" class="popup_view1 btn_white30"><span>상세보기</span></a></span>

        <span th:case="${false}"></span> 

       </div>

      </td>

     </tr>

     </tbody>

     </table>

     <!-- layerpopup : 배포수정 상세보기 -->

     <div class="layer_popup01 layerbox" style="width:630px; display:none;">

      <!-- wrap -->

      <div class="wrap">

       <div class="header">

        <h1><span>배포수정 상세보기</span></h1>

       </div>

       <div class="contents">

        <h2>상세내용</h2>

        <div class="databox scroll-pane">

         <div id="modDesc" class="inner"></div>

        </div>

       </div>

       <p class="close"><a href="#" class="modal_close"><img src="../images/common/btn/btn_close.png" alt="닫기" /></a></p>

      </div>

      <!-- wrap -->

     </div>

     <!-- //layerpopup : 배포수정 상세보기 --> 

    <script type="text/javascript">

    <!-- 

    function fnPopupView(id) {   

     $.ajax({  

      type:"get",  

      dataType: "json",

      cache: false,

      url: "/distribute/get_desc_ajax.json",

      data: {'distSeq':id},

      success: function(data){  

       if(data != null) {

        $("#modDesc").html(data.distInfo.modDetailDesc); 

       }

       

       $(".layer_popup01").modal({

        overlayId: 'layer_popup01',

        containerId: 'layerImageBox01',

        opacity:50,

        overlayCss:{

        backgroundColor:'#000',

        cursor:''

        },

        overlayClose:false,

        onShow: function(dialog) {

            

         $(dialog.container).draggable({

          handle:'div .header'                     

         });

              }

        });

       $(".layer_popup01 .scroll-pane").jScrollPane(

       {

        verticalDragMinHeight: 110,

        verticalDragMaxHeight: 110

       });    

      },

      error: function(xhr,status,err){    

       debug(err);

      }   

     }); 

    }

    // -->

    </script> 

    </div>

    <!-- //board_list -->




    ======================================개발 새발 개발왕===================================




    반응형

    + Recent posts