기존에는 작업을 수행하면 전체 페이지를 재 리로딩 하게 되며 작업을 하였다.
이렇게 새롭게 뷰를 만들어서 연결시켜줘야 할때도 있지만, 기존 뷰에 특정부분만 바뀔때에는
ajax를 통하여 처리하는것이 바람직할 것 같다.
Ajax( Asynchronous Javascript and XML XMLHttpRequest라는 객체를 이용해서 비동기통신
ajax 사용예 (티몬아이디생성시 중복확인처럼)_______________________________________
java
DTO 에 있는 번호비교 ( ajax처리) //실제맵핑=/ajax/exam 클래스고정맵핑있음/ajax
@RequestMapping(value = "/exam", produces = "application/text;charset=utf-8")
@ResponseBody
public String ajaxexam(String no) {
String msg = ""; System.out.println("넘어오는파라미터 : " + no);
try {
if (service.noSearch(no) != null) {
String reusltNo = service.noSearch(no).get(0).getNo();
if (reusltNo.equals(no)) {
msg = "사용불가능 번호 입니다.";
} else {
msg = "사용가능한 번호 입니다.";
}
} else {
msg = "사용가능한 번호 입니다.";
} return msg;
} catch (Exception e) {
msg = "사용가능한 번호 입니다.";
}
return msg;
}
jsp 에서 j쿼리 이용하여 버튼, 동기방식
<script>
$(document).ready(function(){
$("#noajaxbtn").on("click", function () {
location.href="/ggo/ajax/noajax?id="+$("#id1").val();
})
</script>
Ajax 비동기 방식 ( 페이지전환하지 않고 진행 ) <script>
<script>
$("#ajaxbtn").on("click", function () {
var inputdata1 = {"id":$("#name").val()} // 자바로 넘어감//// id는 자바의 매개변수명과 동일하게 맞춰야함(+input박스 id명도 동일하게)
$.ajax({
url: "/ggo/ajax/ajaxtest01", //url : ajax 요청할 path
type: "get", //type : 요청방식 get or post
data: inputdata1, //data : 서버로 전송할 데이터 (보내서 처리할 데이터가 여러개면 json형식으로 처리)
success : success_inputdata1,//success : 서버와 통신이 성공했을 때 호출되는 함수
error: error_inputdata1 //error : 서버와의 통신이 실패했을 때 호출되는 함수
})//end ajax
})//end click
})//end ready
//ajax 요청이 성공하면 .ajax메서드 내부에서 success속성에 설정한 함수를 호출하면서
//ajax의 처리결과를 함수의 매개변수로 전달 - 자동
function success_inputdata1(txt) { // 자바의 결과(return)가 txt로 넘어옴.//txt는 임의로 줘도됨
//alert(txt);
$("#result").html("<h2>jquery" + txt + "</h2>")
}
function error_inputdata1(obj, msg, statusMsg) {
alert("오류발생 : " + obj +", " + msg +", " + statusMsg) ;
}
//obj : ajax통신을 하는 XMLHttpRequest객체,
//msg : 응답메세지
//statusMsg : 에러메세지
/*
url : ajax 요청할 path
type : 요청방식 get or post
data : 서버로 전송할 데이터 (보내서 처리할 데이터가 여러개면 json형식으로 처리)
dataType : ajax처리 결과에 대한 타입 (text,json)
success : 서버와 통신이 성공했을 때 호출되는 함수
error : 서버와의 통신이 실패했을 때 호출되는 함수
*/
</script>
jsp 사용할 위치
<title>Insert title here</title>
</head>
<body>
<h3>Ajax테스트하기</h3>
<form name="myform">
<input type="text" name="id" id="id1"/>
<input type="text" name="name" id="name"/>
<input type="button" id="noajaxbtn" value="no ajax테스트">
<input type="button" id="ajaxbtn" value="ajax테스트">
</form>
<div id="result">${msg }</div>
'스프링MVC' 카테고리의 다른 글
스프링 백업한 프로젝트 import하기 ( ! 느낌표해결 ) (0) | 2023.01.24 |
---|---|
json (0) | 2023.01.18 |
스프링-파일업로드(2) (mybatis사용) (0) | 2023.01.18 |
@PathVariable 사용 (0) | 2023.01.18 |
스프링-파일업로드(1) 작업흐름 (mybatis사용) (0) | 2023.01.18 |