CC292 Labs: Ajax and JSP

Introduction

This is a simple demonstration of how to dynamically generate XML using JSP, and how to consume that XML using asynchronous JavaScript running in a web browser client.

JSP

The JSP file can is below - you can cut and paste this into an editor to run it.  It's the similar to the code we used in the XML lab, except that it changes the start value each time.

<%@ page contentType="text/xml;charset=UTF-8"
language="java" %>
<%! int from = 10, range = 10; %>
<conversions>
<%
  for (int i=from; i<=from+range; i++) {
    %>
    <temperature c="<%= i%>" f="<%= i * 9.0 / 5 + 32%>"/>
    <%
  }
  from++;
%>
</conversions>

When run this should produce a page like this:

JavaScript

The JavaScript to consume this is embedded in this HTML page. (note: it does not do anything unless hooked up to work with an XML document of the type listed above).

Note the use of setTimout.  It is this that makes the page load in a background thread in this example.  It's also possible to to this using a callback specified in the XmlHttpRequest .open() method.  In this example, we passed false, indicating a synchronous call to open().

The main parts are commented, and have been explained in the lectures.

Sample output:

Summary

This example has demonstrated some simple use of Ajax to process dynamically generated XML from a server, and render it as HTML on the client.  Note that there are other ways to achieve similar effects.  It's also possible to load fragments of HTML to render directly, or to load objects in some other encoding (such as JSON (JavaScript Object Notation) for example),

 

end of page