简体   繁体   中英

Javascript XML object - Undefined

The following code brings back my id.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
  }
};
xhttp.open("GET", "https://brewslocal.com/brewery-images-xml", true);
xhttp.send();

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  document.getElementById("photoBox").innerHTML = xmlDoc.getElementsByTagName("image")[0].id;
}
<div id="photoBox"></div>

When I change to the next attribute imageurl it comes back undefined.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
  }
};
xhttp.open("GET", "https://brewslocal.com/brewery-images-xml", true);
xhttp.send();

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  document.getElementById("photoBox").innerHTML = xmlDoc.getElementsByTagName("image")[0].imageurl;
}
<div id="photoBox"></div>

Any ideas?

You can use Element.getAttribute('attributeName') to get the attribute value from this custom HTML element.

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  document.getElementById("photoBox").innerHTML = xmlDoc.getElementsByTagName("image")[0].getAttribute('imageurl');
}

You can do like this

function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName('title')[0];
var y = x.childNodes[0];
document.getElementById("demo").innerHTML =
y.nodeValue; 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM