I will keep this very short:
I’m trying to make a loop through an xml-document for a gallery. I got a script that should work, but doesn’t. Can anyone please tell me where I did wrong?
I didn’t want to make this longer because the problem is simple and have been pondering over this since yesterday and this is the closest I get.
I want to loop through the xml-file and print out “path” and “file” first and most. I’m building a gallery and thought that the best way to save all the data for the images was an xml-file, but now I can’t get it to loop correctly. In the script I made the page print out both x and i, which resulted with x being 1 and i being 0, hence it hasn’t worked through the for-loop at all as I see it.
Any help would be appreciated, because I’m stuck. Been trying so many solutions that my head is spinning and I can’t get any further without a nudge in the right direction.
The html/javascript:
<script type="text/javascript">
function displayResult()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","../gallery/gallery.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("session");
for (i=0;i<x.length;i++)
{
img = "<img src='";
path = (x[0].getElementsByTagName("path")[0].childNodes[0].nodeValue);
file = (x[i].getElementsByTagName("file")[i].childNodes[0].nodeValue);
end = "' /><br />";
name = (x[i].getElementsByTagName("name")[i].childNodes[0].nodeValue);
txt = "x:" + x.length + "| i " + i + "<br />" + img + path + file + end + name + "<br />";
document.getElementById("content").innerHTML = txt;
//document.write(txt);
}
}
</script>
</head>
<body onload="displayResult()">
<div id='content'></div>
</body>
</html>
xml-file:
<gallery>
<session>
<path>../gallery/beauty/</path>
<item>
<file>_DSC2331.jpg</file>
<name>Picture 1</name>
</item>
<item>
<file>_DSC2339.jpg</file>
<name>Picture 2</name>
</item>
<item>
<file>_DSC2350.jpg</file>
<name>Picture 3</name>
</item>
<date>2011-08-03</date>
</session>
</gallery>
If I can make some suggestions:
varkeyword within functions to make those variables local to that function. The code you have at the moment would set values in the global namespace, which is often considered bad practice (e.g. you could overwrite other people’s variables, or other people could overwrite yours). Also declare your variables at the start of a function, as they will be hoisted there anyway.itemsas well assessions..