EN
JavaScript Ajax POST request with Java Spring MVC controller
1 points
In JavaScript, it is possible to make an AJAX POST request in the following way.
Note: scroll to See also section to see other variants of AJAX requests.
In this section XMLHttpRequest
object usage to make a POST request is presented.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<script>
5
6
var xhr = new XMLHttpRequest();
7
8
xhr.onreadystatechange = function() {
9
if (xhr.readyState === XMLHttpRequest.DONE) {
10
if (xhr.status === 200) {
11
document.body.innerText = 'Response: ' + xhr.responseText;
12
} else {
13
document.body.innerText = 'Error: ' + xhr.status;
14
}
15
}
16
};
17
18
var data = 'This is my data';
19
20
xhr.open('POST', '/examples/echo', true);
21
xhr.send(data);
22
23
</script>
24
</body>
25
</html>
In this section simple Spring backend that handles POST method requests is presented.
xxxxxxxxxx
1
import org.springframework.stereotype.Controller;
2
import org.springframework.web.bind.annotation.RequestBody;
3
import org.springframework.web.bind.annotation.RequestMapping;
4
import org.springframework.web.bind.annotation.RequestMethod;
5
import org.springframework.web.bind.annotation.ResponseBody;
6
7
8
public class EchoPostController {
9
10
value = "/examples/echo", method = RequestMethod.POST) (
11
12
public String makePostEcho( String data) {
13
return data;
14
}
15
}