I have the following JavaScript (see below). The script requests an XML file from the server and displays it on the page.

The script works fine when the requested XML file is stored on the same server as the script.

The problem is when I try requesting an XML file from an external server such as the National Weather Service. I get an error. If I take the XML file from the National Weather Service and save it to my server it works. Why can't I use my script to request XML files stored on external servers?

Thanks in advance for any help.

Javascript Code
Code:
window.onload = initAll;
var xhr = false;

function initAll() {
document.getElementById("makeTextRequest").onclick = getNewFile;
document.getElementById("makeXMLRequest").onclick = getNewFile;
}

function getNewFile() {
makeRequest(this.href);
return false;
}

function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}

if (xhr) {
xhr.onreadystatechange = showContents;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}

function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.contentType=="text/xml") {
var outMsg = xhr.responseXML.getElementsByTagName("choices")[0].textContent;
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
}
HTML Code
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My First Ajax Script</title>
<script type="text/javascript" src="script01.js"></script>
</head>
<body>
<p><a id="makeXMLRequest" href="http://www.weather.gov/xml/current_obs/KOJC.xml">Request an XML file</a></p>
<div id="updateArea">&nbsp;</div>
</body>
</html>