xhttp请求多次返回



我正在发送一个xhttp请求,以从XML文件中检索一些元素。然而,它似乎返回了大约8次:前6次不完整,另外2次返回XML中的所有项。很明显,我只想要一次完整的。

XML文件位于http://www.boardgamegeek.com/xmlapi/collection/Zuiderspel?own=1&版本=1

该网站位于http://i298619.iris.fhict.nl/zuiderspel/spellen/正如你所看到的,游戏会显示多次(游戏《炼金术士》应该显示两次,但例如游戏《99次机会》会在列表中返回多次)。

查看控制台,了解我的意思。

我如何才能阻止请求多次返回,使每个游戏只显示一次?

我的代码:

<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>

readystatechange事件不能保证请求完成。这只是意味着它改变了readyState

您需要做的是检查readyState是否为4(DONE),然后调用您的函数。当请求完成时,还会触发其他事件,例如loadloadend

最新更新