0

我有个问题。我想加载一个 XML 文件并从中提取特定节点以使用 JavaScript 进行显示。

我找到了以下教程:http ://www.w3schools.com/dom/dom_nodes_get.asp

基于此,我尝试了自己的方法,但它不起作用,我不知道我做错了什么。

所以基本上我想在 XML 文档中加载天气预报,例如这个:http ://weather.yahooapis.com/forecastrss?w=2442047&u=c

假设我想读取第一个值,即节点“标题”。

现在基于教程,我使用了以下脚本:

<!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>

但我没有得到任何结果。谁能帮我在哪里犯错?

4

3 回答 3

1

这很可能与同源政策有关。这意味着您不能从运行 JavaScript 的域以外的域获取数据。

进一步解释一下,如果我有一个页面,www.example.com/我可以使用该函数从中获取 xml 文件,www.example.com/example1/data.xml但我不允许从www.someothersite.com. 有一些方法可以解决这个问题:绕过同源策略的方法

您可以在此处阅读更多相关信息:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript

于 2013-07-12T15:30:39.917 回答
0
//
//  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...
//
于 2013-08-12T17:40:26.973 回答
0

您需要将 XML 文件放在自己的域中。不允许跨域请求。

于 2013-07-12T15:32:25.320 回答