Accessing MVC with Ajax


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.

image from book
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!



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

Similar book on Amazon
HTML, XHTML, and CSS Bible
HTML, XHTML, and CSS Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
PHP and MySQL Web Development (4th Edition)
PHP and MySQL Web Development (4th Edition)

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net