XML响应文本未定义

时间:2019-07-01 11:07:59

标签: javascript html

我正在呼叫外部服务器,并获得有效的响应并返回数据。如果我将这些数据转储到console.log()中,则可以看到所需的数据。但是,返回的数据是XML,如果我尝试在响应文本上使用getElementsByTagName方法,则会收到错误Uncaught TypeError: searchResults.getElementsByTagName is not a function。我检查后发现searchResults未定义,这是我的问题,我不确定该如何解决。

function getBggData() {
  var searchTerm = document.getElementById("searchTerm").value;
  // console.log("Search Term = " + searchTerm);
  var httpURL = "https://www.boardgamegeek.com/xmlapi2/search?type=boardgame,boardgameexpansion&query=" + searchTerm
  // console.log("URL used is = " + httpURL);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      displayData(this);
    }
  };
  xhttp.open("GET", httpURL, true);
  xhttp.send();
};

function displayData(xml) {
  var i;
  var searchResults = xml.responseText;
  console.log(searchResults.type);
  console.log(searchResults);
  var table = "<tr><th>Game</th><th>Year Released</th></tr>";
  var x = searchResults.getElementsByTagName("item");
  document.getElementById("resultsHeader").innerHTML = "Search Results = " + x + " items.";
  document.getElementById("searchResults").innerHTML = table;
};

2 个答案:

答案 0 :(得分:1)

您可以这样做

var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml,"text/xml");
console.log(xmlDoc.getElementsByTagName("title")[0]);

在这里,我们解析xml并将其获取到变量xmlDoc

答案 1 :(得分:0)

var searchResults = xml.response XML ;