記錄

jquery) Ajax 본문

Web/Jquery

jquery) Ajax

surhommejk 2018. 3. 22. 16:06

JavaScript로 만든 Ajax

(+ https://developer.mozilla.org/ko/docs/Web/Guide/AJAX/Getting_Started 참고)


  <script type="text/javascript">
    /*
      1. XMLHttpRequest 객체 얻기
      2. onreadystatechange 이벤트 핸들러 구현
      3. 요청 정보 ( open() )
      4. 요청 보내기 (send() )
      5. 응답 처리 (Text(JSON), xml )
    */
    var httpReq=null;
    function getInstance(){
      
       if(window.XMLHttpRequest){
//모든 브라우져 > XMLHttpRequest
httpReq = new XMLHttpRequest();
         }else if(window.ActiveXObject){ // <<- for 구 브라우저
           httpReq = new ActiveXObject("Msxml2.XMLHTTP");
         }else{
         throw new Error("AJAX 지원하지 않습니다");
         }
       return httpReq;
    }
    function sendData(){
      httpReq = getInstance();
      httpReq.onreadystatechange = Handlerstatechange; //(X) 생략
      var keys = document.getElementById("emp").value;
      httpReq.open("post", "Ex05_EmpSearch.jsp?empno="+keys);
      httpReq.send();
    }
    //이벤트에 달아줄 핸들러 함수 구현(onreadystatechange)
    function Handlerstatechange(){
     if(httpReq.readyState == 4){
     if(httpReq.status >= 200 && httpReq.status < 300){
       //받는 데이터가지고 UI 구성하기
       document.getElementById("txtdata").innerHTML = httpReq.responseText;
       
       }
       }
    }
  </script>









jQuery로 만든 Ajax


/*
     https://www.w3schools.com/jquery/jquery_ref_ajax.asp 참조 페이지
     Jquery Ajax 작업 : xmlHttpRequest 객체를 사용하는 다양한 함수를 제공
     Jquery Ajax : 다양한 비동기 작업을 할 수 있는 함수 제공

     1. Global Ajax Event Handlers
     2. Helper Functions
     3. Low-Level Interface (40 %)
     4. Shorthand Methods (50 %)
    
  
   $(selector).load(url,data,function(response,status,xhr))
     url Type: String A string containing the URL to which the request is sent.
data Type: PlainObject or String A plain object or string
that is sent to the server with the request.
     [complete] Type: Function( String responseText, String textStatus, jqXHR jqXHR)
     A callback function that is executed when the request completes.
    
    load함수
    1. 서버에서 받는 데이터가 (html, text 형식)
    2. client 특정 요소에 삽입을 목적 (innerHTML 기능 포함)
*/

$(function(){ //load 되면
      $('#btn').click(function() {
//비동기 함수
        $('#display').load("Ex01_Ajax_load.jsp",
           {"msg":$('#msg2').val()},
           function(responseText, statusText , xhr){
           //responseText : 서버가 응답한 결과값 (Text , xml)
            //200 , 500 : 문자리턴 >> success , error
            //xhr : xmlHttpRequest 객체의 주소값 (설정 정보)
           if(statusText == "success"){
            //응답이 왔고 4 ,, 응답이 정상건 200
              alert('load success:200~299 :' + responseText);
           }else{
             //응답이 왔고 4 ,, 응답이 500 , 404 ....
               alert("load fail : " + xhr.status + ": " + xhr.statusText);
        }
     });
      });
    });










Ajax 요소별 설명 (예시 1)


        $(function(){
            $('#message').click(function() {
                jQuery.ajax(
                        {
                            // 받아올 페이지 주소
                            url:"Ex02_menu.html",
                            
                            //서버가 client 응답 형식 : html
                            dataType:"html",
                            
                            //서버가 응답한 코드 (200~299) 라면
                            //Function( Anything data, String textStatus, jqXHR jqXHR )
                            //responsedata 를 통해서 응답한 데이터 받겠다
                            success:function(responsedata){
                                
                                $('#menudiv').html(responsedata);
                    }
                });
                
            });
        });




Ajax 요소별 설명 (예시 2) -> Apollo에서 썼던 것

$.ajax(
       {
       type : "post",
       url : "changesubtask.htm",
       data : {
            'subtaskid': subtaskid,
            'tid' : tid,
            'subtask_fini_or_unfini' : subtask_fini_or_unfini
       },
       success : function(rdata){
           
       } // end-success
       }); // end-ajax





Ajax 요소별 설명 (예시 3)


$(function(){
$('#login').click(function(){
var actionurl= $('#form1').attr('action');
//actionurl > Ex08_Ajax_loginok.jsp
//attr() , val() , text() , html()
var form_data = {
user_id:$('#user_id').val(),
user_pw:$('#user_pw').val()
}   
$.ajax(
{
//전송 타입
type:"POST",
//전송 주소
url:actionurl,
//jsp?user_id=hong&user_pw=1003
data:form_data,
//서버가 클라이언트 전달하는 문서의 타입
dataType:"html",
success:function(responsedata){
//서버가 응답한 데이터가 : text, html 빈 문자열
console.log(">" + responsedata + "<");
//javascript 공백 제거 함수
var result = responsedata.trim();
console.log(">"+result+"<");
},
error:function(xhr){
alert('error :' + xhr.status + "/" + xhr.statusText);
}
}       
); // end - .ajax
}); // end - click
}); // end - function



cf)

보낼 것이 있을 때) type, data를 밝혀 주어야 함(ex: type:"POST", data:변수명)

보낼 것이 없을 때) type, data를 빼면 된다




여러 개의 변수를 보내고 싶으면 json 형태로 data를 설정

$.ajax(
{
type: "POST",
url:"deletepoint.db",
data:{userid:testid, contentnumber:contentnum},
dataType:"json",
success:function(rdata){
$("#mybtn").click();
},
error:function(xhr){
alert('error :' + xhr.status + "/" + xhr.statusText);
}

}
); // end - ajax



실전예제 Ajax (+ servlet)

<script type="text/javascript">
    $(function() {
        
        $('#emp_btn').click(function() {
            $('#targetdiv').empty();
            var empno = $('#search_empno').val();

            jQuery.ajax({

                // 받아올 페이지 주소(전송주소)
                url : "Listservlet",

                // 전송타입
                type : "get",

                // 보내는 data
                data : {
                    "empno" : empno
                },

                //서버가 client 응답 형식 : html
                dataType : "json",

                success:function(data){
                    //$('#targetdiv').empty();
                    console.log(data);
                    
                    var tablestr = '<table class="table table-bordered">';
                    tablestr += '<th>EMPNO</th><th>ENAME</th><th>JOB</th><th>MGR</th>
<th>HIREDATE</th><th>SAL</th><th>COMM</th><th>DEPTNO</th><th>수정하기</th><th>삭제하기</th> ';
                    $.each(data,function(index,obj){
                        tablestr+='<tr>';
                        tablestr+='<td>' + obj.empno + '</td>';
                        tablestr+='<td>' + obj.ename + '</td>';
                        tablestr+='<td>' + obj.job + '</td>';
                        tablestr+='<td>' + obj.mgr + '</td>';
                        tablestr+='<td>' + obj.hiredate + '</td>';
                        tablestr+='<td>' + obj.sal + '</td>';
                        tablestr+='<td>' + obj.comm + '</td>';
                        tablestr+='<td>' + obj.deptno + '</td>';
                        tablestr+='<td><a class="btn btn-primary"
href="memberedit?empno=${' + obj.empno + '} id = "toggleNavColor">' + '수정' + '</a></td>';
                        tablestr+='<td><a class="btn btn-primary"
href="EmpDelete?empno=${' + obj.empno + '} id = "toggleNavColor">' + '삭제' + '</a></td>';
                        tablestr+='</tr>';
                    }); 
                    tablestr+= '</table>';
                    $('#targetdiv').append(tablestr);
                    
                } // end - success
            }); // end - ajax
        }); // end - click
        
        
        $('#empno_btn').click(function() {

            $('#targetdiv').empty();
            var empno = $('#search_empno').val();

            jQuery.ajax({

                // 받아올 페이지 주소(전송주소)
                url : "EmpSearch",

                // 전송타입
                type : "get",

                // 보내는 data
                data : {
                    "empno" : empno
                },

                //서버가 client 응답 형식 : html
                dataType : "json",

                success:function(data){
                    //$('#targetdiv').empty();
                    console.log(data);
                    
                    var tablestr = '<table class="table table-bordered">';
                    tablestr += '<th>EMPNO</th><th>ENAME</th><th>JOB</th><th>MGR</th>
<th>HIREDATE</th><th>SAL</th><th>COMM</th><th>DEPTNO</th><th>수정하기</th><th>삭제하기</th> ';
                    $.each(data,function(index,obj){
                        tablestr+='<tr>';
                        tablestr+='<td>' + obj.empno + '</td>';
                        tablestr+='<td>' + obj.ename + '</td>';
                        tablestr+='<td>' + obj.job + '</td>';
                        tablestr+='<td>' + obj.mgr + '</td>';
                        tablestr+='<td>' + obj.hiredate + '</td>';
                        tablestr+='<td>' + obj.sal + '</td>';
                        tablestr+='<td>' + obj.comm + '</td>';
                        tablestr+='<td>' + obj.deptno + '</td>';
                        tablestr+='<td><a class="btn btn-primary"
href="memberedit?empno=${' + obj.empno + '} id = "toggleNavColor">' + '수정' + '</a></td>';
                        tablestr+='<td><a class="btn btn-primary"
href="EmpDelete?empno=${' + obj.empno + '} id = "toggleNavColor">' + '삭제' + '</a></td>';
                        tablestr+='</tr>';
                    }); 
                    tablestr+= '</table>';
                    $('#targetdiv').append(tablestr);
                    
                } // end - success
            }); // end - ajax
        }); // end - click
    }); // end - function

</script>
<script type="text/javascript">

$("select").change(function () {
    $('#targetdiv').empty();
    var deptno = $('#search_deptno').val();
    
    jQuery.ajax({

        // 받아올 페이지 주소(전송주소)
        url : "dept",

        // 전송타입
        type : "get",

        // 보내는 data
        data : {
            "deptno" : deptno
        },

        //서버가 client 응답 형식 : html
        dataType : "json",

        success:function(data){
            //$('#targetdiv').empty();
            console.log(data);
            
            var tablestr = '<table class="table table-bordered">';
            tablestr += '<th>EMPNO</th><th>ENAME</th><th>JOB</th><th>MGR</th>
<th>HIREDATE</th><th>SAL</th><th>COMM</th><th>DEPTNO</th><th>수정하기</th><th>삭제하기</th> ';
            $.each(data,function(index,obj){
                tablestr+='<tr>';
                tablestr+='<td>' + obj.empno + '</td>';
                tablestr+='<td>' + obj.ename + '</td>';
                tablestr+='<td>' + obj.job + '</td>';
                tablestr+='<td>' + obj.mgr + '</td>';
                tablestr+='<td>' + obj.hiredate + '</td>';
                tablestr+='<td>' + obj.sal + '</td>';
                tablestr+='<td>' + obj.comm + '</td>';
                tablestr+='<td>' + obj.deptno + '</td>';
                tablestr+='<td><a class="btn btn-primary"
href="memberedit?empno=${' + obj.empno + '} id = "toggleNavColor">' + '수정' + '</a></td>';
                tablestr+='<td><a class="btn btn-primary"
href="EmpDelete?empno=${' + obj.empno + '} id = "toggleNavColor">' + '삭제' + '</a></td>';
                tablestr+='</tr>';
            }); 
            tablestr+= '</table>';
            $('#targetdiv').append(tablestr);
            
        } // end - success
    }); // end - ajax
    
});
</script>



servlet

package kr.or.bit.servlet;
import java.util.*;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.bit.dao.Empdao;
import kr.or.bit.utils.Emp;
import net.sf.json.JSONArray;

@WebServlet("/EmpSearch")
public class EmpSearch extends HttpServlet {
    private static final long serialVersionUID = 1L;
public EmpSearch() {
}

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        doProcess(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        doProcess(request, response);
    }

    private void doProcess(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        
         request.setCharacterEncoding("UTF-8");
         response.setContentType("text/html;charset=UTF-8");
    
         int empno = Integer.parseInt(request.getParameter("empno"));

         Empdao dao = new Empdao();
         Emp emp = dao.emp_search(empno);
         ArrayList<Emp> Emplist = new ArrayList<>();
        
         if(emp != null) {
             Emplist.add(emp);
         }
        
         JSONArray jsonlist = JSONArray.fromObject(Emplist);
         response.getWriter().print(jsonlist);
        
    }   
}


package kr.or.bit.servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.or.bit.dao.Empdao;
import kr.or.bit.utils.Emp;
import net.sf.json.JSONArray;

/**
* Servlet implementation class dept
*/
@WebServlet("/dept")
public class dept extends HttpServlet {
    private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public dept() {
super();
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
      doProcess(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
      doProcess(request, response);
  }

  private void doProcess(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
      
       request.setCharacterEncoding("UTF-8");
       response.setContentType("text/html;charset=UTF-8");
  
       int deptno = Integer.parseInt(request.getParameter("deptno"));
       System.out.println(deptno);
      
       ArrayList<Emp> Emplist = new ArrayList<>();
       Empdao dao = new Empdao();
       Emplist = dao.dept_search(deptno);
              
       JSONArray jsonlist = JSONArray.fromObject(Emplist);
       response.getWriter().print(jsonlist);
      
  }   
}


'Web > Jquery' 카테고리의 다른 글

jquery) jquery ui datepicker 형식 설정  (0) 2018.04.14
jquery) Ajax + 외부 API  (0) 2018.03.27
jquery&json) 연습문제  (0) 2018.03.16
jquery) .each, empty&remove  (0) 2018.03.16
jquery) selector, event, get, set, add  (0) 2018.03.15
Comments