EN
JavaScript Ajax GET request with Java Spring MVC controller
10 points
In JavaScript, it is possible to make AJAX GET requests in the following way.
Note: scroll to See also section to see other variants of AJAX requests.
In this section XMLHttpRequest
object has been used to make a GET request.
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
xhr.open('GET', '/examples/echo?text=hello', true);
19
xhr.send(null);
20
21
</script>
22
</body>
23
</html>
In this section simple Spring backend that handles GET method requests is presented.
xxxxxxxxxx
1
import org.springframework.stereotype.Controller;
2
import org.springframework.web.bind.annotation.*;
3
4
5
public class EchoGetController {
6
7
value = "/examples/echo", method = RequestMethod.GET) (
8
9
public String makeGetEcho( ("text") String text) {
10
return text;
11
}
12
}