简体   繁体   中英

Using JavaScript to replace HTML content with content from an external XML file?

I'm trying to connect an XML file generated by an API with a (currently) static webpage, which can be found at oliverpwilson.github.io/tubular . I have an HTML file structured roughly like so:

<div>
    <span id="content">No Content Yet</span>
</div>

and some Javascript in the <header> to determine what goes in the <span> :

<script>
      function myFunction() {
      document.getElementById("content").innerHTML = "Some Content Now!";
</script>

and <body onload="myFunction"> so it triggers on load.

This all works.

What I want to do is use an external XML file generated by an API (the Transport for London API, to be precise), hosted at a URI http://cloud.tfl.gov.uk/TrackerNet/LineStatus , parse it for information using javascript, and use that information to update what my

document.getElementById("content").innerHTML = "Some Content Now!";

displays inside the quotes, ie replacing "Some Content Now!" with whatever the XML file generates that exists inside a certain tag, for example <Status Description="Good Service"> , where "Some Content Now!" would be replaced by "Good Service".

I hope that broadly makes sense. I have no idea how to go about this so any help would be appreciated.

I have looked at your website what you have been posted. In there you have such elements, these elements have the following structure:

div xxx-line
 |--- div details
       |--- div status
       |--- div details

With these you have the option to chance directly what you want in the javascript. You can call it via the id from 'status' or 'details' or you go over the classes 'div xxx-line', feel free.

The xml you can read with the following code:

if (window.DOMParser)
{
  parser=new DOMParser();
  xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async=false;
  xmlDoc.loadXML(txt);
}

And with this, you get the information from the nodes:

//Get status
var status = xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue;

//Get details
var details = xmlDoc.getElementsByTagName("status")[0].childNodes[0].nodeValue;

with the variable status or details you can replace the content of the div's

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