2012-02-12 155 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)。