2012-02-12 158 views
0

我想弄清楚如何从未在我自己的网站上托管的XML文件中提取数据。我完全不熟悉这个,所以我不知道我要出错的地方。我可以轻松地从我自己的站点获取这些数据。任何帮助将不胜感激,谢谢!从外部网站拉取XML数据

<script type="text/javascript"> 
    if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    url = "http://elcu.herobo.com/testarea/include/cd_catalog.xml" 
    xmlhttp.open("GET",url,false); 
    xmlhttp.send(); 
    xmlDoc=xmlhttp.responseXML; 

    document.write("<table border='0' cellpadding='1' cellspacing='1' width'90%' id='1' class='tablesorter'><thead><tr> <th>Artist</th> <th>Title</th> <th>Country</th></thead><tbody>"); 

    var x=xmlDoc.getElementsByTagName("CD"); 
    for (i=0;i<x.length;i++) 
    { 
     document.write("<tr><td>"); 
     document.write(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue); 
     document.write("</td><td>"); 
     document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue); 
     document.write("</td><td>"); 
     document.write(x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue); 
     document.write("</td></tr>"); 
    } 
    document.write("</tbody></table>"); 

回答

0

出于安全考虑,您是,在默认情况下,不允许做跨域请求得到XML数据(same-origin policy)。如果你想跨域获取数据,你通常需要使用JSON-P作为你的格式,或者在你自己的域中设置一个可以访问数据的代理。

0

我以为我永远不会写这个,但是,“你可能会考虑使用jQuery。”它为不同浏览器提供了所有功能,并且还支持CORS所需的JSON-P,除非您可以让服务器开始返回CORS头以允许访问。

0

如果您有权访问该页面,该页面不在服务器上托管(我想您没有),您可以使用JSONP(有关更多详细信息,请参见answer),否则您应该使用PROXY(请参阅此answer)。