# Spring09

제로·2023년 1월 18일
0

Spring

목록 보기
9/18
post-thumbnail

스프링과 jquery를 연동한 ajax처리

  1. ajax는 단계별로 처리할 수 있다.
    1) 순수 js처리
    XMLHttpRequest js 객체를 활용하여
    - 서버안에 text 호출
    - 서버안에 jsp(화면) 호출
    - 서버안에 jsp(json데이터) 호출
    - 서버안에 jsp controller(json데이터) 호출

    2) jquery로 처리

    • $.ajax({속성1:속성값,...})

    • 속성
      - url : 요청주소, 자원을 호출하는 것을 말한다
      ex) $.ajax({"url":"${path}/empAjax.do"})
      - data : 요청값 전달(query string 형식)
      1단계 : data:"id="+$("#id").val()+"&pass="+$("#pass").val()
      2단계 : data:{id:"himan",pass:"7777"}
      3단계 : data:${"form"}.serialize()
      form객체에 포함된 요소객체를 name, value에 의해 자동 query string으로 만들어준다.
      - type : get/post
      - dataType : 결과로 받은 데이터 유형 (json, xml, text)
      - success : 서버에서 전달받았을 때 에러없을시 readyState==4, stautus==200일 때 사용하는 메서드
      ex) success:function(data){
      data:받은 데이터/객체
      }
      - error : 에러발생시 사용할 기능 메서드
      ex) error:function(xhr, status, error){}

      3) spring 서버단 json 데이터 처리 및 jquery 활용 호출
      - json view단 컨테이너 설정으로 객체 ==> json 문자열로 처리
      - @RestController를 통한 문자열 데이터 호출 및 josn 데이터 호출 처리
      4) spring + jquery 연동 처리
      - 초기 화면 로딩
      - 이벤트에 의해 jquery로 서버단 호출(요청값)
      - 서버단 json데이터 클라이언트 전달
      - 클라이언트 json데이터를 객체화하여 화면 구성 및 출력

      @@ Controller.java
      	@Controller 
         public class A02_Controller {
             // http://localhost:7080/springweb/empForAjax.do
             @GetMapping("/empForAjax.do") // 초기화면 세팅
             public String empForAjax() {
                 return "a01_jquery\\a17_ajax.html";
             }
         }
      @@ RestController.java
      	@RestController  //json데이터를 만들어주는 controller
      	public class A01_RestController {
         	private A02_EmpDao dao;
             // http://localhost:7080/springweb/callRest06.do
             @RequestMapping(value="/callRest06.do",
              		// 한글이 출력되도록 encoding
                     produces="text/plain;charset=UTF-8")
             public String callRest06(Emp sch) {
                 A02_EmpDao dao = new A02_EmpDao();
                 Gson g = new Gson();
                 if(sch.getEname()==null) sch.setEname("");
                 if(sch.getJob()==null) sch.setJob("");
                 if(sch.getToSal()==0) sch.setToSal(9999);
                 return g.toJson(dao.getEmpSch(sch)); 
             }
         }
      @@ View.html
       <script type="text/javascript">
           $(document).ready(function(){
               $("h2").text("jquery Ajax(사원정보 검색)")
               $("input").on({keyup:function(){
               	// form 전체 내용을 쿼리스트링 형식으로 만들어줌
               	var qstr=$("form").serialize() 
              	 /*
                   var enameVal = $("[name=ename]").val()
                   var jobVal = $("[name=job]").val()
                   var frSalVal = $("[name=frSal]").val()
                   var toSalVal = $("[name=toSal]").val()
                   var qstr = "ename="+enameVal+"&job="+jobVal+"&frSal="+frSalVal+"&toSal="+toSalVal
                   */
                   $.ajax({
                    		// 호출할 json 주소 @RestController 부분
                       url:"/springweb/callRest06.do",
                       type:"post",
                       data:qstr,
                       dataType:"json",
                       success:function(empList){
                           var addHTML=""
                           $(empList).each(function(idx, emp){// idx가 먼저
                               addHTML+="<tr>"
                               addHTML+="<td>"+emp.empno+"</td>"
                               addHTML+="<td>"+emp.ename+"</td>"
                               addHTML+="<td>"+emp.job+"</td>"
                               addHTML+="<td>"+emp.sal+"</td>"
                               addHTML+="<td>"+emp.comm+"</td>"
                               addHTML+="<td>"+emp.deptno+"</td>"
                               addHTML+="</tr>"
                           })
                           $("table tbody").html(addHTML)
                       },
                       error:function(xhr,status,error){
                           console.log(xhr)
                           console.log(status)
                           console.log(error)
                       }
                   })
      
               }})
           });
       </script>
       

업로드중..



profile
아자아자 화이팅

0개의 댓글

관련 채용 정보