ASP AJAX

AJAX는 전체 페이지를 다시 로드하지 않고 웹 페이지의 일부를 업데이트 하는 것임.

AJAX = Asynchronouse JavaScript ans XML의 약자로 동적인 웹페이지를 만드는 기술임.
AJAX는 인터넷 표준을 기반으로 다음을 조합하여 사용함.

  • XMLHttpRequest 객체 : 서버와 비동기적으로 데이터 교환
  • JavaScript/DOM : 정보 표시 / 상호작용
  • CSS
  • XML : 종종 데이터 전송 형식으로 사용됨.

나머지 기초적인 설명은 패스하도록 함.

 

Example 1

  <% @CODEPAGE="65001" language="vbscript" %>
  <% session.CodePage = "65001" %>
  <% Response.CharSet = "utf-8" %>
  <% Response.buffer=true %>
  <% Response.Expires = 0 %>
  <!DOCTYPE html>
  <html lang="ko">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      * { background-color : black; color : white; margin : 1em; }
    </style>
    <title>The XMLHttpRequest Object</title>
  </head>
  <body>
    <head>
      There are <%=application( "visitors" )%> on online now!
    </head>
    <h1>Start typing a name in the input field below</h1>
    <br/><hr/><br/>

    <form action="">
      <label for="txt">INPUT</label>
      <input
        type="text" name="txt" id="txt"
        onkeyup="showHint(this.value)"
      />
    </form>

    <p>Suggestions : <span id="hint"></span></p>

    <script>
      const showHint = ( str ) => {
        let xhttp;

        if( str.length == 0 ) {
          document.getElementById( 'hint' ).innerHTML = '';
          return;
        }

        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
          if( this.readyState == 4 && this.status == 200 ) {
            document.getElementById( 'hint' ).innerHTML = this.responseText;
          }
        };

        xhttp.open( 'GET', '01-getHint.asp?q=' + str, true);
        xhttp.send();
      }
    </script>

  </body>
  </html>
  <% @CODEPAGE="65001" language="vbscript" %>
  <% Response.buffer = true %>
  <%
    response.expires = -1

    ' array 선언
    dim arr(30)
    arr(1) = "Anna"
    arr(2) = "Brittany"
    arr(3) = "Dianna"
    arr(4) = "Eva"
    arr(5) = "Fiona"
    arr(6) = "Gunda"
    arr(7) = "Hege"
    arr(8) = "Inga"
    arr(9) = "Johanna"
    arr(10) = "Kitty"
    arr(11) = "Linda"
    arr(12) = "Nina"
    arr(13) = "Ophelia"
    arr(14) = "Petunia"
    arr(15) = "Amanda"
    arr(16) = "Raquel"
    arr(17) = "Cindy"
    arr(18) = "Doris"
    arr(19) = "Eve"
    arr(20) = "Evita"
    arr(21) = "Sunniva"
    arr(22) = "Tove"
    arr(23) = "Unni"
    arr(24) = "Violet"
    arr(25) = "Liza"
    arr(26) = "Elizabeth"
    arr(27) = "Ellen"
    arr(28) = "Wenche"
    arr(29) = "Vicky"
    arr(30) = "cinderella"


    ' QueryString에서 q의 값 가져오기
    q = ucase( request.querystring( "q" ) )

    if len( q ) > 0 then
      hint = ""
      for i = 0 to 30
        if q = ucase( mid( arr( i ), 1, len( q ) ) ) then
          if hint = "" then
            hint = arr( i )
          else
            hint = hint & ", " & arr( i )
          end if
        end if
      next
    end if

    ' hint가 없다면 "No Suggestion"
    ' 있다면 hint
    if hint = "" then 
      response.write( "No Suggestion" )
    else
      response.write( hint )
    end if

  %>

 

 

Example 2 : AJAX 데이터 베이스 연결

DB 연결은 당장 여건이 안되므로 스킵 해둔다.

 


728x90
반응형

'WEB > ASP' 카테고리의 다른 글

[ASP IIS] 윈도우 10 IIS 및 클래식 ASP 설정  (0) 2021.09.06
[ASP] global.asa  (0) 2021.08.30
[ASP] #include  (0) 2021.08.27
[ASP] 어플리케이션  (0) 2021.08.27
[ASP] 세션  (0) 2021.08.27

pom.xml

pom.xml에 다음과 같은 Dependency를 추가 해 준다.
버전에 따라 지원이 되지 않을 수 있다.

<!-- JSON을 위한 Dependency -->
<dependency>
  <groupId>net.sf.json-lib</groupId>
  <artifactId>json-lib</artifactId>
  <version>2.4</version>
  <classifier>jdk15</classifier>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.5</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.13</version>
</dependency>
<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-mapper-asl</artifactId>
  <version>1.9.13</version>
</dependency>
<!-- JSON을 위한 Dependency -->

servlet.xml

servlet.xml 혹은 dispatcher-servlet.xml

<mvc:annotation-driven>
  <mvc:message-converters>
  
  <!-- 
    이 부분은 Controller에서 일반적인 HTML을 리턴하기 위한 설정이다.
    JSON을 리턴하지 않을 경우는 Default 값으로 지정 되어 있기 때문에 설정 할 필요 없지만,
    JSON 리턴과 HTML 리턴을 모두 하려면은 명시적으로 설정 해 줘야 한다.
   -->
    <bean class="org.springframework.http.converter.StringHttpMessageConverter">
      <property name="supportedMediaTypes">
        <list>
          <value>text/html; charset=UTF-8</value>
        </list>
      </property>
    </bean>
    
    <!--
      Controller에서 JSON 리턴시 객체를 변환 해주기 위해서 MessageConverter가 필요하다. 
    -->
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
      <property name="supportedMediaTypes">
        <list>
          <value>application/json; charset=UTF-8</value>
        </list>
      </property>
    </bean>
    
  </mvc:message-converters>
</mvc:annotation-driven>

Controller

Controller는
필수적으로 @ResponceBody
권장 사항으로 produces = "application/json; charset=UTF-8" 를 명시 해 준다.
produces 속성은 Response의 Content-Type을 제어한다.

@RequestMapping(
    value = "/reqWaterDepth.do",
    method = RequestMethod.POST,
    produces = "application/json; charset=UTF-8")
@ResponseBody
public Map<String, List<WaterDepthDTO>> reqWaterDepth (
    HttpServletRequest req,
    HttpServletResponse res,
    @RequestParam Map<String, String> area
      ) throws Exception {
  logger.info("\n\tREQ Water Depth . do \n" + area.get("area") + "\n");
  return service.getWaterDepthInRange(area.get("area"));
}

Ajax Request

Request 부분에서는 딱히 설정할 것이 없다.

function getData(area) {
  return new Promise(function(resolve, reject) {
    console.group('drawSurvArea getData');
    area = {
      'area' : area
    };
    //  console.log( area );
    $.ajax({
      type : "POST",
      url : "/reqWaterDepth.do",
      data : area,
      dataType : 'json',
      beforeSend : function(xhr, opts) {
        console.log("before send");
        // when validation is false
        if (false) {
          xhr.abort();
        }
      },
      success : function(res) {
        console.log("SUCCESS");
        console.log(res);
        if (Object.keys(res).length === 0
            && JSON.stringify(res) === JSON.stringify({})) {
          alert('해당 영역에 수심데이터가 없습니다.');
          return;
        } else {
          resolve(res);
        }
      },
      error : function(err) {
        console.log("ERR");
        console.error(err.statusText);
        alert('데이터를 처리 하던중 에러가 발생했습니다.\n' + err.statusText + ' : ' + err.status);
        reject(err);
      }
    });
    console.groupEnd('drawSurvArea getData');
  })
}
getData(area).then(function(data) {
  console.log('THEN')
  console.log(data);
});
728x90
반응형

+ Recent posts