So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest
object in JavaScript. Here's a Firefox compatible example:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
alert(data);
}
}
xhr.open('GET', 'myservlet', true);
xhr.send(null);
</script>
This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.get('myservlet', function(data) {
alert(data);
});
</script>
Either way, the Servlet on the server should be mapped on an url-pattern
of /myservlet
(you can change this to your taste) and have at least doGet()
implemented and write the data to the response as follows:
String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);
This should show Hello World!
in the JavaScript alert.
You can of course also use doPost()
, but then you should use 'POST'
in xhr.open()
or use $.post()
instead of $.get()
in jQuery.
Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a
<div id="data"></div>
in the HTML where you'd like to display the response data, then you can do so instead of alert(data)
of the 1st example:
document.getElementById("data").firstChild.nodeValue = data;
In the jQuery example you could do this in a more concise and nice way:
$('#data').text(data);
To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. The last one is most preferred since it's more concise and can be used in both Java and JavaScript on a very easy manner. In Java, you can use Google Gson to convert fullworthy Java objects to JSON and vice versa.
List<Product> products = productDAO.list(); // Product is just a Javabean with properties `id`, `name` and `description`.
String json = new Gson().toJson(products);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
In JavaScript you can use jQuery's $.getJSON()
to get it "instantly". Let's display it in a <table>
.
$.getJSON('myservlet', function(data) {
var table = $('<table>').appendTo($('#data'));
$.each(data, function(i, product) {
var row = $('<tr>').appendTo(table);
$('<td>').text(product.id).appendTo(row);
$('<td>').text(product.name).appendTo(row);
$('<td>').text(product.description).appendTo(row);
});
});
See also: