Ajax 사용방법

2021. 11. 26. 09:14JQuery

 

// 방법1 예전방식
$.ajax({
url: "/send", // 데이터를 요청할 url
type: "GET", // GET, POST, DELETE, PATCH, PUT 등
data : data, // 보내고 싶은 데이터를 JSON 형식으로 작성
success: function(result){ // 요청에 성공했을때 실행되고 서버에서 받은 데이터를 확인할수 있다
console.log(result);
},
error: function(){
console.log("에러발생");
}
})
// 방법2 추천방식
$.ajax({
url: "/send",
type: "GET",
data : data,
})
.done(function(result){ // 요청에 성공했을때 실행
console.log(result);
})
.fail(function(){
console.log("에러발생");
})

 

 

컨트롤러에서 데이터 받기

html, js

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<span>에이작스 테스트</span>
<input type="text" class="name">
<button>전송</button>
<script>
$("button").click(function(){
const data = {
name : $(".name").val()
};
$.ajax({
url: "/send",
type: "GET",
data : data,
})
.done(function(result){
console.log(result);
})
.fail(function(){
console.log("에러발생");
})
})
</script>
</body>
</html>

 

컨트롤러

@Controller
public class AjaxTest {
@GetMapping("/ajaxTest")
public String ajaxTest() {
return "ajaxTest";
}
// ajax 요청을 받는곳
@ResponseBody
@GetMapping("/send")
public String send(String name) {
System.out.println("name = " + name);
return "안녕하세요 " + name + "님";
// throw new NullPointerException();
}
}

Mapping을 ajax type과 맞춰주고 @ResponseBody를 붙여준다

컨트롤러는 요청이 들어오면 return 값을 viewResolver로 전달 => 알맞는 화면을 보여주는데

 

@ResponseBody 어노테이션을 붙이면

return 값을 MessageConerveter로 전달 => 값이 String이면 String으로 객체이면 JSON으로 변환후 응답해준다

 

 

 

 

String으로 return 했을때

 

 

Object로 return  했을때

@ResponseBody
@GetMapping("/send")
public Map<String, String> send(String name) {
Map<String, String> map = new HashMap<>();
map.put("msg1", "안녕하세요1");
map.put("msg2", "안녕하세요2");
map.put("msg3", "안녕하세요3");
return map;
}

요청성공 함수에서 result["msg1"] 식으로 값을 꺼내볼수 있다

 

 

 

배열을 서버로 전달하고 싶을때는 traditional : true 를 추가해주면 된다

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<span>에이작스 테스트</span>
<input type="text" class="name1">
<input type="text" class="name2">
<input type="text" class="name3">
<button>전송</button>
<script>
$("button").click(function(){
const data = {
name : [
$(".name1").val(), // 안녕하세요
$(".name2").val(), // 테스트
$(".name3").val() // 입니다
]
};
$.ajax({
url: "/send",
type: "GET",
data : data,
traditional : true // 추가
})
.done(function(result){
console.log(result);
})
.fail(function(){
console.log("에러발생");
})
})
</script>
</body>
</html>

 

컨트롤러

@ResponseBody
@GetMapping("/send")
public void send(String[] name) {
System.out.println(Arrays.toString(name));
}
// 결과 [안녕하세요, 테스트, 입니다]

 

'JQuery' 카테고리의 다른 글

선택된 input[type="checkbox"] 값 가져오기  (0) 2021.11.24
swal 사용방법  (0) 2021.11.24
선택된 input[type="radio"] 값 가져오기  (0) 2021.11.24