Load XML file AJAX

This code handles loading external XML file and uses this data. You have to remember setting Internet privilege for external scripts and data.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
var xmlhttp;
var txt,x,xx,i;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    txt="<table border='1'><tr><th>Title</th><th>Author</th><th>Price</th></tr>";
    x=xmlhttp.responseXML.documentElement.getElementsByTagName("book");
    for (i=0;i<x.length;i++)
      {
      txt=txt + "<tr>";
      xx=x[i].getElementsByTagName("title");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
      xx=x[i].getElementsByTagName("author");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
        xx=x[i].getElementsByTagName("price");
          {
          try
            {
            txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
            }
          catch (er)
            {
            txt=txt + "<td> </td>";
            }
          }
      txt=txt + "</tr>";
      }
    txt=txt + "</table>";
    document.getElementById('BooksInfo').innerHTML=txt;
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="BooksInfo">
<button onclick="loadXMLDoc('http://www.w3schools.com/xsl/books.xml')">Books Info</button>
</div>
</body>
</html>

Responses

0 Replies