[jQuery] jQuery Ajax XML / JSON

sang·2024년 3월 27일

jQuery

화면의 동적 기능을 js 보다 좀 더 쉽고 편리하게 개발할 수 있게 해주는 js 기반 라이브러리

특징

CSS 선택자
메소드 체인 방식
풍부한 플러그인
크로스 브라우징

사용방법

방법 1. 라이브러리 다운로드
방법 2. 네트워크 CDN 호스트 설정

<!-- 지정 버전 jQuery 사용 -->
<script src="http://code.jquery.com/jquery-2.2.1.min.js"></script>
<!-- 가장 최신 버전 jQuery 사용 -->
<script src="http://code.jquery.com/jquery-latest.min.js"></script>

jQuery 선택자

$("*"): 모든 DOM(HTML 객체) 선택
$("#id")
$("elementName")
$(".className")
$("selector1, selector2, ..."): 해당 선택자를 가지는 DOM 선택



Ajax

클라이언트 작업과 상관없이 비동기적으로 서버 작업 수행 시 사용
페이지 이동 미발생

웹 페이지 처리 방식 비교

  • JSP
    개인정보 입력 - 서버 요청 - 서버 결과 처리 - 클라이언트 브라우저에 HTML 태그 전송 - 페이지 이동 및 출력
  • Ajax
    개인정보 입력 - 서버 요청 - 서버 결과 처리 - 요청한 페이지로 XML/JSON 전송

사용법

$.ajax({
  type: "post 또는 get",
  async:"true 또는 false",
  url: "요청할 URL",
  data: {서버로 전송할 데이터 },
  dataType: "서버에서 전송받을 데이터형식",
  success:{
      //정상 요청, 응답 시 처리
  },
  error: function(xhr,status,error){
      //오류 발생 시 처리
  },
  complete:function(data,textStatus){
      //작업 완료 후 처리
  }
});

pro16/src/sec01/ex01/AjaxTest1.java

package sec01.ex01;
...
@WebServlet("/ajaxTest1")
public class AjaxTest1 extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doHandle(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    doHandle(request, response);
  }
  private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    String param = (String)request.getParameter("param"); //ajax로 전송된 매개변수 가져오기
    System.out.println("param = " +param);
    PrintWriter writer = response.getWriter();
    writer.print("안녕하세요! 서버입니다.");
  }
}

pro16/test03/ajax1.html

<script type="text/javascript">
      function fn_process() {
       $.ajax({
        type:"get",
        dataType:”text”,
        async:false,
        url:"http://localhost:8090/pro16/ajaxTest1", //데이터를 전송할 서블릿
        data: {param:"Hello,jquery"},
        success: function(data,textStatus) {
          $('#message').append(data);
        },
        error: function(data,textStatus) {
            alert("에러가 발생했습니다.");
        },
        complete: function(data,textStatus) {
            alert("작업을 완료했습니다");
        }
      });
  }
</script>
</head>
<body>
  <input type="button" value="전송하기" onClick="fn_process()" /><br><br>
  <div id="message"></div>
</body>

Ajax XML

pro16/src/sec01/ex01/AjaxTest2.java

package sec01.ex01;
...
@WebServlet("/ajaxTest2")
public class AjaxTest2 extends HttpServlet {
  private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    String result="";
    PrintWriter writer = response.getWriter();
    
    <!-- 도서 정보 XML -->
    result="<main><book>"+
      "<title><![CDATA[초보자를 위한 자바 프로그래밍]]></title>" +
      "<writer><![CDATA[인포북스 저 | 이병승]]></writer>" +
      "<image><![CDATA[http://localhost:8090/pro16/image/image1.jpg]]></image>"+ "</book>"+ "<book>"+
      "<title><![CDATA[모두의 파이썬]]></title>" +
      "<writer><![CDATA[길벗 저 | 이승찬]]></writer>" +
      "<image><![CDATA[http://localhost:8090/pro16/image/image2.jpg]]></image>"+
      "</book></main>";
    }
}

pro16/WebContent/test03/ajax2.html

<script type="text/javascript">
  function fn_process() {
    $.ajax({
        type:"post",
        async:false,
        url:"http://localhost:8090/pro16/ajaxTest2",
        dataType:"xml", //데이터를 xml로 받음
        success: function (info,textStatus) {
          $(info).find("book").each(function() {
          /*엘리먼트 이름으로 데이터 가져오기*/
          var title=$(this).find("title").text();
          var writer=$(this).find("writer").text();
          var image=$(this).find("image").text();
          
          /*<div id = "bookInfo"> 도서 정보 표시*/
          $("#bookInfo").append( "<p>" +title+ "</p>" + "<p>" +writer + "</p>"+ "<img src="+image + " />" );
          });
        },
        error: function(data,textStatus) {
            alert("에러가 발생했습니다.");
        },
        complete: function(data,textStatus) {
            alert("작업을 완료했습니다");
        }
    });
  }
</script>
</head>
<body>
  <input type="button" value="전송하기" onClick="fn_process()" /><br><br>
  <div id="message"></div>
</body>

ID 중복 여부 확인

pro16/src/sec02/ex01/MemberServlet.java

package sec02.ex01;
 ...
@WebServlet("/mem")
public class MemberServlet extends HttpServlet {
 ...
  private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    PrintWriter writer = response.getWriter();
    
    String id = (String)request.getParameter("id");
    System.out.println("id = " +id);
    
    MemberDAO memberDAO=new MemberDAO();
    boolean overlappedID = memberDAO.overlappedID(id); //ID 중복 여부
    if(overlappedID == true) { writer.print("not_usable"); }
    else{ writer.print("usable"); }
  }
}

pro16/src/sec02/ex01/MemberDAO.java

package sec01.ex02;
 ...
public class MemberDAO {
 ...
  public boolean overlappedID(String id) {
    boolean result = false;
    try {
      con = dataFactory.getConnection();
      String query = "select decode(count(*),1,'true','false') as result from t_member"; //오라클 decode 함수: ID 존재 여부 조회
      query += " where id=?";
      System.out.println("prepareStatememt: " + query);
      pstmt = con.prepareStatement(query);
      pstmt.setString(1, id);
      ResultSet rs = pstmt.executeQuery();
      rs.next();
      result = Boolean.parseBoolean(rs.getString("result")); //String -> Boolean
      pstmt.close();
    } catch (Exception e) { e.printStackTrace(); }
    return result;
  }
}

pro16/WebContent/test03/ajax3.html

<script type="text/javascript">
  function fn_process() {
    var _id = $("#t_id").val();
    if (_id == '') {
      alert("ID를 입력하세요");
      return;
    }
    $.ajax({
      type: "post",
      async: true,
      url: "http://localhost:8090/pro16/mem",
      dataType: "text",
      data: { id: _id },
      success: function (data, textStatus) {
        if (data == 'usable') {
          $('#message').text("사용할 수 있는 ID입니다.");
          $('#btn_duplicate').prop("disabled", true); //버튼 비활성화
        } else {
          $('#message').text("사용할 수 없는 ID입니다.");
        }
      },
      error: function(data,textStatus) {
          alert("에러가 발생했습니다.");
      },
      complete: function(data,textStatus) {
          alert("작업을 완료했습니다");
      }
    });
  }
</script>

</head>
<body>
  <input type="text" id="t_id" />
  <input type="button" id="btn_duplicate" value="ID 중복체크하기" onClick="fn_process()" /><br><br>
  <div id="message"></div> <!-- 결과 표시 -->
</body>
</html>


Ajax JSON

XML보다 단순한 형식
여러 단계의 처리 과정 불필요
빠른 속도
모바일 환경에 유리

사용 시 [JSON 라이브러리 설치] 필요 (https://code.google.com/archive/p/json-simple/downloads)

pro16/WebContent/lib

json-simple-1.1.1.jar 파일 붙여넣기

JSON 자료형


문자열, 제어문자
배열 "배열명": [값1, 값2, 값2, ...]
객체 {"속성명1":속성값1, "속성명2":속성값2, ... }


JSP -> 서블릿

pro16/src/sec03/ex01/JsonServlet1.java

package ex02;
...
@WebServlet("/json")
public class JsonServlet1 extends HttpServlet {
   ...
  private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
  
    String jsonInfo = request.getParameter("jsonInfo"); //전송된 JSON 데이터 가져오기
    try {
        /* JSON 데이터 처리(파싱) */
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonInfo);
        
        System.out.println("* 회원 정보*");
        System.out.println(jsonObject.get("name"));
        System.out.println(jsonObject.get("age"));
        System.out.println(jsonObject.get("gender"));
        System.out.println(jsonObject.get("nickname"));
    { catch(Exception e) { e.printStackTrace(); }
  }
}

pro16/WebContent/test04/json5.jsp

<script>
  $(function() {
    $("#checkJson").click(function() {
      var _jsonInfo ='{"name":"박지성","age":"25","gender":"남자","nickname":"날센돌이"}'; //JSON 형식 데이터 구성
      /* ajax로 데이터 전송 */
      $.ajax({
          type:"post",
          async:false,
          url:"${contextPath}/json",
          data : {jsonInfo: _jsonInfo},
          success:function (data,textStatus) {
        },
        error:function(data,textStatus) {
        alert("에러가 발생했습니다.");
        },
        complete:function(data,textStatus) {
        }
      }); //end ajax
    });
  });
</script>

서블릿 -> JSP

JSON 데이터 가져오기

JSON객체.members.name속성명()

pro16/src/sec03/ex01/JsonServlet3.java

packate sec03.ex01;
...
@WebServlet("/json3")
public class JsonServlet3 extends HttpServlet {
   ...
  private void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html; charset=utf-8");
    PrintWriter writer = response.getWriter();

    JSONObject totaObject = new JSONObject(); //전체 JSON 데이터 객체
    
    /* 회원 배열 */
    JSONArray membersArray = new JSONArray();
    /* 회원 1 */
    JSONObject memberInfo = new JSONObject();
    memberInfo.put("name", "박지성");
    memberInfo.put("age", "25");
    memberInfo.put("gender", "남자");
    memberInfo.put("nickname", "날센돌이");
    membersArray.add(memberInfo);
    /* 회원 2 */
    memberInfo = new JSONObject();
    memberInfo.put("name", "김연아");
    memberInfo.put("age", "21");
    memberInfo.put("gender", "여자");
    memberInfo.put("nickname", "칼치");
    membersArray.add(memberInfo);
    /* 회원 배열 저장 */
    totaObject.put("members", membersArray); 
    
    /* 도서 배열 */
    JSONArray bookArray = new JSONArray();
    /* 도서 1 */
    JSONObject bookInfo = new JSONObject();
    bookInfo.put("title", "초보자를 위한 자바 프로그래밍");
    bookInfo.put("writer", "이병승");
    bookInfo.put("price", "30000");
    bookInfo.put("genre", "IT");
    bookInfo.put("image", "http://localhost:8090/pro16/image/image1.jpg");
    bookArray.add(bookInfo);
    /* 도서 2 */
    bookInfo = new JSONObject();
    bookInfo.put("title", "모두의 파이썬");
    bookInfo.put("writer", "이승찬");
    bookInfo.put("price", "12000");
    bookInfo.put("genre", "IT");
    bookInfo.put("image", "http://localhost:8090/pro16/image/image1.jpg");
    bookArray.add(bookInfo);
    /* 도서 배열 저장 */
    totaObject.put("books", bookArray);
    
    String jsonInfo = totaObject.toJSONString(); //JSON -> String
    System.out.print(jsonInfo);
    writer.print(jsonInfo); //브라우저로 전송
  }
}

pro16/WebContent/test04/json7.jsp

<script>
  $(function () {
    $("#checkJson").click(function () {
      $.ajax({
        type: "post",
        async: false,
        url: "${contextPath}/json3",
        success: function (data, textStatus) {
          /* JSON 데이터 파싱 */
          var jsonInfo = JSON.parse(data);
          
          var memberInfo = "회원 정보<br>";
          memberInfo += "=======<br>";
          for (var i in jsonInfo.members) {
            memberInfo += "이름: " + jsonInfo.members[i].name + "<br>";
            memberInfo += "나이: " + jsonInfo.members[i].age + "<br>";
            memberInfo += "성별: " + jsonInfo.members[i].gender + "<br>";
            memberInfo += "별명: " + jsonInfo.members[i].nickname + "<br><br><br>";
          }
          
          var booksInfo = "<br><br><br>도서 정보<br>";
          booksInfo += "===========<br>";
          for (var i in jsonInfo.books) {
            booksInfo += "제목: " + jsonInfo.books[i].title + "<br>";
            booksInfo += "저자: " + jsonInfo.books[i].writer + "<br>";
            booksInfo += "가격: " + jsonInfo.books[i].price + "원 <br>";
            booksInfo += "장르: " + jsonInfo.books[i].genre + "<br>";
            imageURL = jsonInfo.books[i].image;
            booksInfo += "<img src=" + imageURL + " />" + "<br><br><br>";
          }
          $("#output").html(memberInfo + "<br>" + booksInfo);
        },
        error: function (data, textStatus) {
          alert("에러가 발생했습니다.");
        }
      });
    });
  });
</script>


*자바 웹을 다루는 기술

profile
CS 메모장

0개의 댓글