# Ajax 활용하기
## Ajax 란?
페이지의 일부분만 변경하는 기술.
## 왜쓰지?
전체를 바꾸는 거보다 빠름.
## 필요환경
Spring MVC, jQuery
## 사용 예
view
```
// url에 mehod 방식에 맞게 데이터를 보냄.
var request = $.ajax({
url: "/myapp/ajax",
method: "GET",
data: { id: 1234 },
});
// 성공 시, 받아온 데이터가 msg에 담김
request.done(function(msg) {
alert("ajax completed: " + msg)
});
// 실패 시, 결과 출력
request.fail(function(jqXHR, textStatus) {
alert("ajax failed: " + textStatus)
});
```
controller
```
@ResponseBody
@RequestMapping(value = "/ajax", method = RequestMethod.GET)
public String ajax() {
return "GoodJob";
}
```
result
![Imgur](https://i.imgur.com/3jWlGae.png)
## ajax 전달 데이터 받기
view
```
var request = $.ajax({
url: "/myapp/ajax",
method: "GET",
data: { id: 1234,
name: "Sehong Park" }
});
request.done(function(msg) {
alert("ajax completed: " + msg)
});
```
controller
```
@ResponseBody
@RequestMapping(value = "/ajax", method = RequestMethod.GET)
public String ajax(@RequestParam("id") int id, @RequestParam("name") String name) {
return String.format("{ id: %d, name: \"%s\" }", id, name);
}
```
result
![Imgur](https://i.imgur.com/FBGkbn1.png)
---
## JSON 라이브러리 적용
pom.xml
```
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
```
view
```
var request = $.ajax({
url: "/myapp/ajax",
method: "GET",
data: { id: 1234,
name: "Sehong Park" }
});
request.done(function(jsonObj) {
var str = JSON.stringify(jsonObj, null, 2);
alert(str);
});
```
controller
```
@RequestMapping(value = "/ajax", method = RequestMethod.GET)
public @ResponseBody JsonTestVO ajax(@RequestParam("id") int id, @RequestParam("name") String name) {
return new JsonTestVO(id, name);
}
```
vo
```
public class JsonTestVO {
private int id;
private String name;
public JsonTestVO(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
```
result
![Imgur](https://i.imgur.com/Nt8lmVB.png)
---
## Ref.
+ http://www.ibm.com/developerworks/library/j-ajax1/
+ http://api.jquery.com/jquery.ajax/
+ https://blog.hanumoka.net/2018/04/29/spring-20180429-spring-controller-return-json/
+ http://www.nextree.co.kr/p11205/