Warm tip: This article is reproduced from serverfault.com, please click

Accessing an XML file via URL using HTML and JS

发布于 2020-11-28 05:59:11

I am creating a website that relies on the data of an XML file hosted on a separate domain. In short, if an element in the XML file hosted on HTTP://example.com/test.XML changes from true to false, I want an element of the HTML file on my domain to change. I can achieve this if the XML is in the same directory as my HTML file but I cannot find a solution to the problem of it being on a different domain.

I have tried to use jquery but I am not sure what I am doing wrong. The code I have tried looks like:

$(document).ready(function(){
  var myXML = ""
  var request = new XMLHttpRequest();
  request.open("GET", "http://example.com/test.XML", true);
  request.onreadystatechange = function(){
      if (request.readyState == 4) {
          if (request.status == 200 || request.status == 0) {
              myXML = request.responseXML;
          }
      }
  }
  request.send();
  document.getElementById("test").innerHTML = new XMLSerializer().serializeToString(myXML.documentElement);
});

Please help, and thank you in advance for your time!

Questioner
JonoMN
Viewed
0
farvilain 2020-11-28 14:11:03

Try using the not so recent fetch api.

$(document).ready(function(){
  var myXML = ""
  fetch("http://example.com/test.XML")
  .then( response => response.text()  )
  .then( response => {
    //response is a string containing xml...
    document.getElementById("test").innerHTML = response
  })
  .catch( console.error )
  ;
});

I thing you don't need to serialize the xml, you should just be able to put it directly... but not sure