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.
1. Żądanie POST jQuery AJAX
W tej sekcji metoda $.ajax
służy do wykonania żądania POST.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '/examples/echo-message',
data: {
message: 'hello'
},
success: function(text) {
$(document.body).text('Response: ' + text);
},
error: function (jqXHR) {
$(document.body).text('Error: ' + jqXHR.status);
}
});
});
</script>
</body>
</html>
2. Przykład metod POST serwisu serwera Spring MVC
W tej sekcji przedstawiony jest prosty backend Springa obsługujący żądania metody POST.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class EchoPostController {
@RequestMapping(value = "/examples/echo-message", method = RequestMethod.POST)
@ResponseBody
public String sendPostMessage(@RequestParam("message") String message) {
return message;
}
}