2

I would like to fetch data from an XML file to a JS variable (I would like to use pure JS, no jQuery). But I have always get error while downloading the file:

var url = "http://www.w3schools.com/xml/note.xml";

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function(event){ processRequest(event,xmlhttp); };
xmlhttp.send();

function processRequest(event,xmlhttp) {
    if(xmlhttp.readyState != 4) return;
    alert("status: " +xmlhttp.status);
}

The response xml is always empty - the response status is 0.

1

2 Answers 2

1

Its because it violates the Same origin policy.

Do:

  1. GO to w3School website.
  2. Open developer console.
  3. Paste and run your code and you will get the result
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the answer. It is just strange that the browser itself can send crossDomain requests (e.g. simply opening the url), but JS is not able to do so.
DON'T go to w3schools, Please, don't. here's why. I'd recommend either quirksmode or MDN for good, reliable documentation... or even JavaScriptKit
1

Try local url. Your code doesn't match same origin policy

p.s. w3schools is not where you want to learn, mdn and dochub.io ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.