0

I am trying to make a simple XML parse to get data from a XML file and use it in my JavaScript application. Here is my code:

JS parse:

function loadXMLDoc(dname) 
{
if (window.XMLHttpRequest)
  {
  xhttp=new XMLHttpRequest();
  }
else
  {
  xhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}

Body script:

xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");

function SHOW(){
    document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue;
}

HTML:

<button id="dan" onclick="SHOW()">SHOW</button>
<p id="demo"></p>

And here is a demo which does not work: http://jsfiddle.net/2XEzh/

Any idea how to make it working? Thanks in advance.

Daniel JJ
  • 191
  • 4
  • 16

1 Answers1

1

It would be great practice to review your console before you send your question.

Chrome Console Message

XMLHttpRequest cannot load http://www.w3schools.com/dom/books.xml. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

It means, the browser is blocking it. Browsers usually allows the request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS

cilerler
  • 9,010
  • 10
  • 56
  • 91
  • Thank you for your answer. But I tried to follow W3 tutrial for making this parser. [XML DOM Load Functions](http://www.w3schools.com/dom/dom_loadxmldoc.asp). I checked the link you provided, but it was so complicated for me. :/ – Daniel JJ Jun 23 '14 at 20:29
  • You are welcome. I suggest you to read the article step by step and ask the questions when you don't understand the concept and don't forget to include the paragraph as reference. _sorry no easy way out :) we are not here to write code for you, but will always be here to support each other ;-) you will get your answers as long as you don't give it up_ Briefly, you can't do it on client side alone, you also have to do additional steps on your server to support CORS, unless your server supports CORS. You may also want to check this one http://stackoverflow.com/a/17875201/439130 – cilerler Jun 23 '14 at 22:08