Reputation: 27
I'm sending a xhttprequest to retrieve some elements from a XML file. However, it seems to return about 8 times: the first 6 times incomplete, the other 2 it returns all items from the XML. Obviously, I only want it once and complete.
The XML file is found at http://www.boardgamegeek.com/xmlapi/collection/Zuiderspel?own=1&version=1
The website is found at http://i298619.iris.fhict.nl/zuiderspel/spellen/ As you can see, games are shown multiple times (the game 'Alchemist' should be shown twice as it is, but for example the game '99 Chances' is returned several times in the list).
Check the console to see what I mean.
How could I stop the request from returning multiple times so every game gets just shown once?
My code:
<script type="text/javascript">
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (true) {
myFunction(xhttp);
}
};
xhttp.open("GET", "../wp-content/uploads/2015/12/Zuiderspel.xml", true);
xhttp.send();
}
function myFunction(xml) {
console.log(xml);
var x, i, xmlDoc, table, spellen, newDiv, newDivImg, stand, jaar, minspelers, maxspelers, speeltijd;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml.responseText, "application/xml");
x = xmlDoc.getElementsByTagName("item");
for (i = 0; i < x.length; i++) {
spellen = x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
thumbs = x[i].getElementsByTagName("thumbnail")[0].childNodes[0].nodeValue;
stand = x[i].getElementsByTagName("comment")[0].childNodes[0].nodeValue;
jaar = x[i].getElementsByTagName("yearpublished")[0].childNodes[0].nodeValue;
newDiv = document.createElement("div");
newDiv.id = "div" + i;
newDiv.className = "spelClass";
newDiv.style.backgroundImage = "url(" + thumbs + ")";
newDiv.innerHTML = "<b>" + spellen + "</b><br />" + stand + "<br />" + jaar;
document.getElementById("spellen").appendChild(newDiv);
}
}
loadDoc();
</script>
<div id="spellen">
</div>
Upvotes: 0
Views: 241
Reputation: 14423
The readystatechange
event doesn't guarantee that the request is done. It just means that it changed readyState
.
What you need to do is to check if readyState
is 4
(DONE) and then call your function. There are other events that trigger when the request is done, such as load
or loadend
.
Upvotes: 1