Magazine
 
Quick Review:Ajax
 

Five common Ajax patterns

 

function loadUrl( url ) { ... }
function getMore()
{
var url = window.location.toString();
url = url.replace( /pat1_readmore.html/, ‘pat1_readmore_content.html’ );
loadUrl( url );
}
</script>
<body>
<h1>Walking the dog</h1>
I took my dog for a walk today.
<span id=”moreSpan”>
<a href=”javascript: void getMore()”>Read more...</a>
</span>
</body>
</html>

Listing 7 shows the content for the “read more” section.

Listing 7. Pat1_readmore_content.html

It was a nice day out. Warm and sunny. My dog liked getting out for a stretch.

This code demonstrates the use of the <span> tag instead of the <div> tag. The approach you use depends on the requirements of your user interface (UI). But as you can see, it’s easy to use either approach.

Getting new HTML for the page is one thing, but what about when you want the JavaScript code on the page to actually do something intelligent with the data. How do you get the data to the browser in a structured way? Why XML, of course.

Pattern 2. Reading XML data

For some reason, Ajax has become synonymous with XML, even though XML isn’t strictly required. As you can see from the examples above, you can return straight text or even fragments of HTML — or Extensible HTML (XHTML) — code. But sending XML can have its rewards.

Listing 8 shows Ajax code that requests records about books from the server, then displays that data in a table within the page.

Listing 8. Pat2_xml.html

<html>
<head>
<script>
var req = null;
function processReqChange() {
if (req.readyState == 4 && req.status == 200 && req.responseXML ) {
var dtable = document.getElementById( ‘dataBody’ );
var nl = req.responseXML.getElementsByTagName( ‘book’ );
for( var i = 0; i < nl.length; i++ ) {

Apr 2008 | Java Jazz Up | 68
previous
index
next
 
Pages: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,

30
, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53 , 54, 55, 56, 57,

58
, 59, 60, 61, 62, 63 , 64, 65 , 66 , 67 , 68 , 69 , 70, 71, 72, 73, 74, 75, 76, 77, 78,   Download PDF