Dengar's Blog Logo

Dengar's blog...
We will see what I post, probably will be some random tutorials

Thursday, 6 June 2013

Using AJAX to read XML

arguably not the wisest of all implementations of an AJAX, i have prepared a page on my personal website (http://www.matenaers.com/chris/chris-matenaers.html) to put my CV online - at least a basic version.

i finished with the code, but still have to fill in the rest of the xml file to complete this task. this will change the content of a div on hovering over another div...

finally, this here is code only, apologies. ask questions if you have to.

here is a copy of the solution:

xml part:
<?xml version="1.0" encoding="UTF-8"?>
<lvl1>
    <lvl2 id="aaa">
        <lv3a attrib="test_attribute">node_text</lv3a>
        <lvl3b><![CDATA[
            Some data not parsed
            ]]></lvl3b>
    </lvl2>
</lvl1>


and the html & javascript:
<script>
function getXML(url) {
var xmlhttp;
var txt = "";
var x,xx,i;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
x = xmlhttp.responseXML.documentElement.getElementsByTagName("lvl2");
for (i=0;i<x.length;i++) {
txt = txt + "<br />Attribute lvl2 : " + x[i].getAttribute('id');
xx = x[i].getElementsByTagName('lv3a');
txt = txt + "<br />Node value lvl3a : " +  xx[0].firstChild.nodeValue;
txt = txt + "<br />Attribute lvl3a : " +  xx[0].getAttribute('attrib');
xx = x[i].getElementsByTagName('lvl3b');
txt = txt + "<br />Node value lvl3b : " +  xx[0].firstChild.nodeValue;
}
document.getElementById("change_me").innerHTML=txt;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
<h1>Chris' Sandbox</h1>
<div id="mainpage">
<div id="content" class="text">
<h4><a href="#" onmouseover="getXML('http://www.matenaers.com/chris/code/sample_xml.xml')" onclick="return false;">Hover here!</a></h4>
<hr/>
<div id="change_me"> test </div>
</div>
</div>

No comments: