Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - Ajax-Enabled Rich Internet Applications

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Using XML and the DOM

When passing structured data between the server and the client, Ajax applications often use XML because it is easy to generate and parse.

Using XML and the DOM

 

When passing structured data between the server and the client, Ajax applications often use XML because it is easy to generate and parse. When the XMLHttpRequest object re-ceives XML data, it parses and stores the data as an XML DOM object in the responseXML property. The example in Fig. 15.8 asynchronously requests from a server XML docu-ments containing URLs of book-cover images, then displays the images in an HTML ta-ble. The code that configures the asynchronous request is the same as in Fig. 15.5. You can test-drive this application at test.deitel.com/examples/iw3htp4/ajax/fig15_08/ PullImagesOntoPage.html (the book-cover images will be easier to see on the screen).

 

1    <?xml version = "1.0" encoding = "utf-8"?>

 

2    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

3          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4              

5    <!-- Fig. 15.8: PullImagesOntoPage.html -->

 

6    <!-- Image catalog that uses Ajax to request XML data asynchronously. -->

 

7    <html xmlns = "http://www.w3.org/1999/xhtml">

 

8    <head>

 

9    <title> Pulling Images onto the Page </title>

 

10  <style type = "text/css">

 

11         td { padding: 4px }

 

12         img { border: 1px solid black }

 

13  </style>

 

14  <script type = "text/javascript" language = "Javascript">

 

15         var asyncRequest; // variable to hold XMLHttpRequest object

16

17         // set up and send the asynchronous request to the XML file

 

18         function getImages( url )

19         {

 

20               // attempt to create the XMLHttpRequest and make the request

21               try

22               {

 

23                      asyncRequest = new XMLHttpRequest(); // create request object

24          


 

25                      // register event handler

 

26                      asyncRequest.onreadystatechange = processResponse;

 

27                      asyncRequest.open( 'GET', url, true ); // prepare the request

 

28                      asyncRequest.send( null ); // send the request

 

29                } // end try

 

30                catch ( exception )

31                {

 

32                      alert( 'Request Failed' );

 

33                } // end catch

 

34         } // end function getImages

35

36         // parses the XML response; dynamically creates a table using DOM and

 

37         // populates it with the response data; displays the table on the page

 

38         function processResponse()

39         {

 

40                // if request completed successfully and responseXML is non-null

 

41                if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 &&

 

42                      asyncRequest.responseXML )

43                {

 

44                      clearTable(); // prepare to display a new set of images

45

46                      // get the covers from the responseXML

 

47                      var covers = asyncRequest.responseXML.getElementsByTagName(

48                            "cover" )

49                       

 

50                      // get base URL for the images

 

var baseUrl = asyncRequest.responseXML.getElementsByTagName(

"baseurl" ).item( 0 ).firstChild.nodeValue;                      

54                      // get the placeholder div element named covers

 

55                      var output = document.getElementById( "covers" );

56          

57                      // create a table to display the images

 

58                      var imageTable = document.createElement( 'table' );

59          

60                      // create the table's body

 

61                      var tableBody = document.createElement( 'tbody' );

62          

63                      var rowCount = 0; // tracks number of images in current row

 

64                      var imageRow = document.createElement( "tr" ); // create row

65          

66                      // place images in row

 

67                      for ( var i = 0; i < covers.length; i++ )

{

var cover = covers.item( i ); // get a cover from covers array

           

// get the image filename   

var image = cover.getElementsByTagName( "image"   ).

item( 0 ).firstChild.nodeValue;      

           

// create table cell and img element to display    the image

var imageCell = document.createElement( "td" );         

77        var imageTag = document.createElement( "img" );

78       

79        // set img element's src attribute

80        imageTag.setAttribute( "src", baseUrl + escape( image ) );

81        imageCell.appendChild( imageTag ); // place img in cell

82        imageRow.appendChild( imageCell ); // place cell in row

83        rowCount++; // increment number of images in row

84       

85        // if there are 6 images in the row, append the row to

86        // table and start a new row

87        if ( rowCount == 6 && i + 1 < covers.length )

88        {

89        tableBody.appendChild( imageRow );

90        imageRow = document.createElement( "tr" );

91        rowCount = 0;

92                            } // end if statement

 

93                      } // end for statement

94          

95                      tableBody.appendChild( imageRow ); // append row to table body

 

96                      imageTable.appendChild( tableBody ); // append body to table

 

97                      output.appendChild( imageTable ); // append table to covers div

 

98                } // end if

 

99         } // end function processResponse

100

101     // deletes the data in the table.

 

102      function clearTable()

103      {

 

104             document.getElementById( "covers" ).innerHTML = '';

 

105      }// end function clearTable

 

106      </script>

 

107    </head>

108    <body>

 

109      <input type = "radio" checked = "unchecked" name ="Books" value = "all"

 

110             onclick = 'getImages( "all.xml" )'/> All Books

 

111      <input type = "radio" checked = "unchecked"

 

112             name = "Books" value = "simply"

 

113             onclick = 'getImages( "simply.xml" )'/>  Simply Books

 

114      <input type = "radio" checked = "unchecked"

 

115             name = "Books" value = "howto"

 

116             onclick = 'getImages( "howto.xml" )'/> How to Program Books

 

117      <input type = "radio" checked = "unchecked"

 

118             name = "Books" value = "dotnet"

 

119             onclick = 'getImages( "dotnet.xml" )'/> .NET Books

 

120      <input type = "radio" checked = "unchecked"

 

121             name = "Books" value = "javaccpp"

 

122             onclick = 'getImages( "javaccpp.xml" )'/> Java, C, C++ Books

 

123      <input type = "radio" checked = "checked" name = "Books" value = "none"

 

124             onclick = 'clearTable()'/> None

125      <br/>

 

126      <div id = "covers"></div>

 

127    </body>

 

</html>





Fig. 15.8 | Image catalog that uses Ajax to request XML data asynchronously.

 

 

When the XMLHttpRequest object receives the response, it invokes the callback function processResponse (lines 38–99). We use XMLHttpRequest object’s responseXML property to access the XML returned by the server. Lines 41–42 check that the request was successful, and that the responseXML property is not empty. The XML file that we requested includes a baseURL node that contains the address of the image directory and a collection of cover nodes that contain image filenames. responseXML is a document object, so we can extract data from it using the XML DOM functions. Lines 47–52 use the DOM’s method getElementsByTagName to extract all the image filenames from cover nodes and the URL of the directory from the baseURL node. Since the baseURL has no child nodes, we use item(0).firstChild.nodeValue to obtain the directory’s address and store it in variable baseURL. The image filenames are stored in the covers array.

 

As in Fig. 15.5 we have a placeholder div element (line 126) to specify where the image table will be displayed on the page. Line 55 stores the div in variable output, so we can fill it with content later in the program.

 

Lines 58–93 generate an XHTML table dynamically, using the createElement, setAttribute and appendChild DOM methods. Method createElement creates an XHTML element of the specified type. Method setAttribute adds or changes an attribute of an XHTML element. Method appendChild inserts one XHTML element into another. Lines 58 and 61 create the table and tbody elements, respectively. We restrict each row to no more than six images, which we track with variable rowCount variable. Each iteration of the for statement (lines 67–93) obtains the filename of the image to be inserted (lines 69–73), creates a table cell element where the image will be inserted (line 76) and creates an <img> element (line 77). Line 80 sets the image’s src attribute to the image’s URL, which we build by concatenating the filename to the base URL of the XHTML document. Lines 81–82 insert the <img> element into the cell and the cell into the table row. When the row has six cells, it is inserted into the table and a new row is cre-ated (lines 87–92). Once all the rows have been inserted into the table, the table is inserted into the placeholder element covers that is referenced by variable output (line 97). This element is located on the bottom of the web page.

 

Function clearTable (lines 102–105) is called to clear images when the user switches radio buttons. The text is cleared by setting the innerHTML property of the placeholder ele-ment to the empty string.

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.