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.
1. Pure JavaScript (Vanilla JS) AJAX GET request
In this section XMLHttpRequest
object has been used to make a GET request.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status == 200) {
document.body.innerText = 'Response: ' + xhr.responseText;
} else {
document.body.innerText = 'Error: ' + xhr.status;
}
}
};
xhr.open('GET', '/examples/echo?text=hello', true);
xhr.send(null);
</script>
</body>
</html>
2. Spring MVC server site GET methods example
In this section simple Spring backend that handles GET method requests is presented.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class EchoGetController {
@RequestMapping(value = "/examples/echo", method = RequestMethod.GET)
@ResponseBody
public String makeGetEcho(@RequestParam("text") String text) {
return text;
}
}