EN
jQuery - Ajax POST request with Java Spring MVC controller
14 points
In this article, we're going to have a look at how to make make AJAX POST request with jQuery.
Note: scroll to See also section to see other variants of AJAX requests.
In this section $.ajax
method is used to make POST request.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
5
</head>
6
<body>
7
<script>
8
9
$(document).ready(function() {
10
$.ajax({
11
type: 'POST',
12
url: '/examples/echo-message',
13
data: {
14
message: 'hello'
15
},
16
success: function(text) {
17
$(document.body).text('Response: ' + text);
18
},
19
error: function (jqXHR) {
20
$(document.body).text('Error: ' + jqXHR.status);
21
}
22
});
23
});
24
25
</script>
26
</body>
27
</html>
In this section simple Spring backend that handle 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-message", method = RequestMethod.POST) (
11
12
public String sendPostMessage( ("message") String message) {
13
return message;
14
}
15
}