繁体   English   中英

如何从JavaScript加载外部XML?

[英]How to load an external XML from JavaScript?

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

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

基于此,我尝试了自己的操作,但是它不起作用,并且我不知道自己在做什么错。

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

并说我想读取第一个值,即节点“ title”。

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

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

但是我没有任何结果。 谁能帮助我在哪里出错?

这很可能与相同的原始策略有关。 这意味着不允许您从运行JavaScript的域之外的其他域中获取数据。

进一步说明一下,如果我在www.example.com/有一个页面,则可以使用该功能从www.example.com/example1/data.xml提取xml文件,但不允许我从www.someothersite.com提取数据www.someothersite.com 有解决此问题的方法规避同源政策的方法

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

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

//
//  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...
//

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM