Reputation: 485
I have a problem. I want to load an XML file and extract particular nodes from it for displaying using JavaScript.
I have found the following tutorial: http://www.w3schools.com/dom/dom_nodes_get.asp
And based on that I tried my own, but it doesn't work and I don't know what I am doing wrong.
So basically I would like to load a weather forecast in an XML document, for example this one: http://weather.yahooapis.com/forecastrss?w=2442047&u=c
And lets say I want to read the first value, the node "title".
Now based on the tutorial I used the following script:
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"></script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("http://weather.yahooapis.com/forecastrss?w=2442047&u=c");
x = xmlDoc.getElementsByTagName("title");
document.write(x.nodeValue);
</script>
</body>
</html>
But I do not get any result. Could anyone help me where I make the mistake?
Upvotes: 0
Views: 10051
Reputation: 982
//
// you can do that using 'curl-lib', say in php, ( if your server support it, usualy they do ) like this:
//
// create this php file:
//
// doc_reader.php
// ***********************************************************
// <?php
//
// header('Content-Type: '. $_POST['url_mime']);
//
// $url = $_POST['fetch_url'];
//
// $ch = curl_init( $url );
//
// curl_setopt( $ch, CURLOPT_HEADER, false );
// curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
//
// echo curl_exec( $ch );
//
//
// exit;
//
//
// ************************************************************
//
// and put it in the same directory where your page is.
//
// send http post request to the php file ( use jQuery ) :
//
//
$.ajax({
url :'doc_reader.php',
type :'post',
dataType :'xml',
data :{
fetch_url :'http://weather.yahooapis.com/forecastrss?w=2442047&u=c',
url_mime :'application/xml'
},
success:function ( doc ) {
console.log( doc );
}
});
//
// hope it helps...
//
Upvotes: 0
Reputation: 1430
This most likely has to do with the same origin policy. What that means is that you are not allowed to fetch data from another domain than the domain where your JavaScript is running from.
To explain a little further, if I have a page at www.example.com/
I can use the function to fetch xml-files from www.example.com/example1/data.xml
but I am not allowed to fetch data from www.someothersite.com
. There are ways to work around this problem: Ways to circumvent the same-origin policy
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript
Upvotes: 1
Reputation: 165
You need to put the XML files in your own domain.It's not permitted for cross-domain request.
Upvotes: 0