Five common Ajax patterns |
|
The big difference between this page and the pages in the previous pattern is in the processReqChange
function. Instead of looking at responseText, you now look at responseXML, an XML Document
Object Model (DOM) available only if the response from the server was properly encoded XML. Using
responseXML, I request the list of <book> tags from the XML document. I then get the <title> and <author> elements from each. Next, I add a row to the table for each book and cells to each row to
contain the author and title data. This is a pretty rudimentary use of the XML data. More sophisticated
JavaScript code can perform client-side sorting or searching based on the returned data. Unfortunately, the downside of transferring XML data is that it takes some time for the browser to parse through
the XML document. Also, the JavaScript code to find the data in the XML can be complex (as seen
in Listing 8). The alternative is to request JavaScript code from the server.
Pattern 3. Reading JavaScript data
Requesting JavaScript data from the server is a technique that often goes by the classy code name
JavaScript Object Notation (JSON). The value of returning JavaScript data is that it’s efficient for
the browser to parse and creates JavaScript data structures, which are a lot easier to use. Let me
revise the code in Listing 8 that read XML from the server to read JavaScript data from the server,
instead. This new code is shown in Listing 10.
Listing 10. Pat3_js.html
<html><head><script>
var req = null;
function processReqChange() {
if (req.readyState == 4 && req.status == 200 ) {
var dtable = document.getElementById( ‘dataBody’ );
var books = eval( req.responseText );
for( var b in books ) {
var elTr = dtable.insertRow( -1 );
var elAuthorTd = elTr.insertCell( -1 );
elAuthorTd.innerHTML = books[b].author;
var elTitleTd = elTr.insertCell( -1 );
elTitleTd.innerHTML = books[b].title;
} } }
...
All the HTML code remains the same. The processReqChange function simply changes to read an
eval that the JavaScript data returned from the server. The function then uses the JavaScript
objects that come out of the eval as the source of the data, which is then added to the table.
Listing 11 shows the JavaScript data from the server.
Listing 11. Pat3_js_data.js
[ { author: ‘Jack Herrington’, title: ‘Code Generation in Action’ },
{ author: ‘Jack Herrington’, title: ‘Podcasting Hacks’ },
{ author: ‘Jack Herrington’, title: ‘PHP Hacks’ }
] |
|
|
Apr 2008 | Java Jazz Up | 71 |
|
|
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 |
|
|