AJAX XML
AJAX XML instance
AJAX can be used to interactively communicate with XML files.
AJAX XML instance
The example below demonstrates how a webpage uses AJAX to read information from an XML file:
Instance
Try it »
Instance Parsing - loadXMLDoc() function
When the user clicks the "Get my favorite CD" button above, the loadXMLDoc() function is executed.
The loadXMLDoc() function creates an XMLHttpRequest object, adds a function to execute when the server response is ready, and sends the request to the server.
When the server response is ready, an HTML table is constructed, nodes (elements) are extracted from the XML file, and finally, the table element with id="demo" is filled with the XML data:
Asynchronous XML Document Loading
function
loadXMLDoc
(
)
{
var
xhttp
=
new
XMLHttpRequest
(
)
;
xhttp
.
onreadystatechange
=
function
(
)
{
if
(
this
.
readyState
==
4
&&
this
.
status
==
200
)
{
myFunction
(
this
)
;
}
}
;
xhttp
.
open
(
"
GET
"
,
"
cd_catalog.xml
"
,
true
)
;
xhttp
.
send
(
)
;
}
function
myFunction
(
xml
)
{
var
i
;
var
xmlDoc
=
xml
.
responseXML
;
var
table
=
"
ArtistTitle"
;
var
x
=
xmlDoc
.
getElementsByTagName
(
"
CD
"
)
;
for
(
i
=
0
;
i
<
x
.
length
;
i
++
)
{
table
+=
"
"
x
[
i
]
.
getElementsByTagName
(
"
ARTIST
"
)
[
0
]
.
childNodes
[
0
]
.
nodeValue
"
"
x
[
i
]
.
getElementsByTagName
(
"
TITLE
"
)
[
0
]
.
childNodes
[
0
]
.
nodeValue
"
"
;
}
document
.
getElementById
(
"
demo
"
)
.
innerHTML
=
table
;
}
AJAX server page
The server page used in the example above is actually an XML file named "cd_catalog.xml".