On my web page, I have a number of buttons. When clicked, a button will load a given XML file. I want to write the output to the same page as the buttons, but I cannot quite make it all work.
I have multiple entries in my XML file, e.g.:
<nation>
<person>
<named>Cezanne</named>
<profession>Artist</profession>
<work>The Bathers</work>
<flag>flags/flag_France.gif</flag>
</person>
<person>
<named>Gauguin</named>
<profession>Artist</profession>
<work>The Yellow Christ</work>
<flag>flags/flag_France.gif</flag>
</person>
</nation>
This javascript function will read and write all tags:
function getTheFile(theFile){
xmlhttp.open("GET",theFile,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
/*write to the document, set up a for loop to read and write the xml doc*/
document.write("<div>");
var rooty=xmlDoc.getElementsByTagName("person");/*argument passes the root element in xml doc; assigned to variable*/
for(i=0; i<rooty.length; i++){
/*write HTML tag: h1*/
document.write("<h2>");
/*write named xml tag data into h2 tag*/
document.write(rooty[i].getElementsByTagName("named")[0].childNodes[0].nodeValue);
document.write("<img src=");
document.write(rooty[i].getElementsByTagName("flag")[0].childNodes[0].nodeValue);
document.write("/>");
document.write("</h2>"); /*close the h2 tag*/
document.write("<p>");
document.write(rooty[i].getElementsByTagName("profession")[0].childNodes[0].nodeValue);
document.write("<br/>");
document.write(rooty[i].getElementsByTagName("work")[0].childNodes[0].nodeValue);
document.write("</p>");
}
document.write("</div>");/*close the div tag!!*/
}
…but the problem is, this basically writes to a whole new page. A user must navigate back to get to the original buttons.
So, I’ve tried this script:
function getTheFile(theFile){
xmlhttp.open("GET",theFile,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var rooty=xmlDoc.getElementsByTagName("person");/*argument passes the root element in xml doc; assigned to variable*/
for(i=0;i<rooty.length; i++){
/*set variables to hold values of child elements in xml doc*/
namer=(rooty[i].getElementsByTagName("named")[0].childNodes[0].nodeValue);
pro=(rooty[i].getElementsByTagName("profession")[0].childNodes[0].nodeValue);
worker=(rooty[i].getElementsByTagName("work")[0].childNodes[0].nodeValue);
flagged=(rooty[i].getElementsByTagName("flag")[0].childNodes[0].nodeValue);
txt="<h1>" + namer + "<img src=" + flagged + "/></h1>Profession: " + pro + "<br />Famous Work: "+ worker;
document.getElementById("showGuy").innerHTML=txt;
}
}
…which keeps the user on the same page, but only the last XML entry is written to the page.
I see that I need to write a variable to a page element to stay on the page, but somehow that variable needs to hold lots of data. I tried another for loop within the first for loop, but that didn’t work.
Can anyone point me in the right direction? Thanks in advance!