U.f.O
U.f.O

Reputation: 299

How to get file from another server?

I am learning how to perform XHR and placed the code from w3school in my webserver(tomcat7) to try it out. When I placed "note.xml" in the same file as the html, I can use the code below to get the XML file.

xmlhttp.open("GET","note.xml",true); 

However, if I move "note.xml" to another webapp location, I can't use the same method. Neither does the code below is able to get the XML file.

xmlhttp.open("GET","http://localhost:8080/anotherWEBapp/note.xml",true);

HTML:

<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</div>
<script>
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","http://localhost:8080/test-app/note.xml",true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;

document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>

</body>
</html>

Is there anyway I am able to get the XML file with the use of javascript only?

Upvotes: 0

Views: 1110

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187044

Not with pure in browser JS, no.

Cross domain AJAX violates the same origin policy.

The other server needs to allow you do it. One standards compliant way is CORS. But you need to control and modify the remote server to pull this off.

Or, if you have your own server code to tweak, you can proxy things through it. You make an AJAX request on the same domain to something like /proxy?url=http://example.com/somefile.xml. Your server code then fetches that file on the backend and renders it. You dont violate the cross origin policy because the webpage communicates with the same server it loaded from, and what your server does is not it's business.

Or you could use JSONP. But again, this requires cooperation from the remote host that will wrap the content you want in a JS function execution which delivers the content to your page.

Upvotes: 3

Related Questions