Interacting with the MVC code you’ve set up on the server is not difficult-you just have to access the controller using Ajax code. Here’s what that looks like in an Ajax-enabled page, mvc.html, which goes in the chap16 directory on the server. Note that because you set things up appropriately in web.xml, you can refer to the controller servlet simply as Controller:
<html> <head> <title>Ajax and MVC</title> <script language = "javascript"> var XMLHttpRequestObject = false; if (window.XMLHttpRequest) { XMLHttpRequestObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID) { if(XMLHttpRequestObject) { var obj = document.getElementById(divID); XMLHttpRequestObject.open("GET", dataSource); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { obj.innerHTML = XMLHttpRequestObject.responseText; } } XMLHttpRequestObject.send(null); } } </script> </head> <body> <H1>Ajax and MVC</H1> <form> <input type = "button" value = "Display Message" onclick = "getData('Controller', 'targetDiv')"> </form> <div > <p>The fetched data will go here.</p> </div> </body> </html>
The results are shown in Figure 16.7. When you click the Display Message button, the XMLHttpRequest GET request is sent to the controller, which calls the model to get the data to send back, which the controller forwards to the view. The view sends the message back to the browser, which displays the message, as shown in Figure 16.7. Mission accomplished.
Figure 16.7: The MVC application at work
That’s it for putting MVC architecture to work, and that’s it for this book. Happy Ajax programming!