PL
jQuery - żądanie POST Ajax z kontrolerem Java Spring MVC
0 points
W tym artykule przyjrzymy się, jak wykonać żądanie AJAX POST za pomocą jQuery.
Uwaga: przewiń do sekcji Zobacz również, aby zobaczyć inne warianty żądań AJAX.
W tej sekcji metoda $.ajax
służy do wykonania żądania POST.
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>
W tej sekcji przedstawiony jest prosty backend Springa obsługujący żądania metody POST.
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
}