I am making a call to an external server and am getting a valid response back with data. If I dump that data into console.log()
I can see the data that I’m looking for. However the returned data is XML and if I try and use the getElementsByTagName
method on the response text I get the error Uncaught TypeError: searchResults.getElementsByTagName is not a function
. I checked and searchResults
is undefined, which I’m assuming is my problem, I’m just not sure how to fix it.
JavaScript
x
26
26
1
function getBggData() {
2
var searchTerm = document.getElementById("searchTerm").value;
3
// console.log("Search Term = " + searchTerm);
4
var httpURL = "https://www.boardgamegeek.com/xmlapi2/search?type=boardgame,boardgameexpansion&query=" + searchTerm
5
// console.log("URL used is = " + httpURL);
6
var xhttp = new XMLHttpRequest();
7
xhttp.onreadystatechange = function() {
8
if (this.readyState == 4 && this.status == 200) {
9
displayData(this);
10
}
11
};
12
xhttp.open("GET", httpURL, true);
13
xhttp.send();
14
};
15
16
function displayData(xml) {
17
var i;
18
var searchResults = xml.responseText;
19
console.log(searchResults.type);
20
console.log(searchResults);
21
var table = "<tr><th>Game</th><th>Year Released</th></tr>";
22
var x = searchResults.getElementsByTagName("item");
23
document.getElementById("resultsHeader").innerHTML = "Search Results = " + x + " items.";
24
document.getElementById("searchResults").innerHTML = table;
25
};
26
Advertisement
Answer
you can do like this,
JavaScript
1
4
1
var parser = new DOMParser();
2
var xmlDoc = parser.parseFromString(xml,"text/xml");
3
console.log(xmlDoc.getElementsByTagName("title")[0]);
4
here we are parsing the xml and getting it to the variable xmlDoc