0

I'm new to JS and XML. I am following a tutorial for accessing XML file with JavaScript and DOM. Here is my HTML file:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
    myFunction(xhttp);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();

function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName('title')[0];
var y = x.childNodes[0];
document.getElementById("demo").innerHTML =
y.nodeValue; 
}
</script>
</body>
</html>

And here is my XML file books.xml :

<bookstore>
 <book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
 </book>
 <book category="children">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
 </book>
 <book category="web">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
 </book>
 <book category="web" cover="paperback">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
 </book>
</bookstore>

I copied them both from the tutorial but they don't seem to be working for me. When I open the html file I see only a blank page. I tested it on Chrome, IE and MS Edge. What possibly could I be doing wrong ?

VTodorov
  • 953
  • 1
  • 8
  • 25
  • 1
    Open your browser's developer tools. Look in the console. Is there an error message? (The problem is most likely that you aren't using HTTP). – Quentin May 17 '16 at 13:38
  • Yes, I got an error: html.html:15 XMLHttpRequest cannot load file:///C:/Users/Volen/Desktop/%D0%9A%D1%83%D1%80%D1%81%D0%BE%D0%B2%D0%B0%2014/books.xml. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.(anonymous function) @ html.html:15 How can I fix this ? I'm doing this for homework and the html and xml files will be in 1 folder. – VTodorov May 17 '16 at 13:41
  • When I typed the error message into Google, the first result was a Stackoverflow answer that explains that. – Quentin May 17 '16 at 13:42

0 Answers0