2013-02-20 61 views
0

非常簡單的代碼:解析XML的JavaScript不起作用

<!DOCTYPE html> 
<html> 
    <head> 
    </head> 
    <body> 
     <script type="text/javascript">   
      function loadXMLDoc(dname) 
      { 
       if (window.XMLHttpRequest) 
       { 
        xhttp = new XMLHttpRequest(); 
       } 
       else 
       { 
        xhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
       } 
       xhttp.open("GET",dname,false); 
       xhttp.send(); 
       return xhttp.responseXML; 
      } 


      xmlDoc = loadXMLDoc("feedback.xml"); 

      x=xmlDoc.getElementsByTagName("quote"); 
      for (i=0;i<x.length;i++) 
      { 
       document.write(x[i].childNodes[0].nodeValue); 
       document.write("<br>"); 
      } 
     </script>  
    </body> 
</html> 

我加載它看起來像這樣的XML文件 「feedback.xml」:

<feedback> 
    <quote id="1">"This is a quote."</quote> 
    <quote id="2">"This is another quote."</quote> 
</feedback> 

我從http://www.w3schools.com/dom/tryit.asp?filename=try_dom_list_loop的代碼,但沒有真正發生。當我試圖alert(x)來檢查裏面有什麼我得到一個「[對象HTMLCollection]」。但是,當我想檢查alert(x[0])時,我得到「未定義」。任何想法爲什麼這不起作用?看起來很簡單,XML文件與這個html文件位於同一個文件夾中,並且Firebug不會引發任何錯誤。

+0

您是否檢查過XML是否真的返回? – Sirko 2013-02-20 10:59:52

+0

alert(xmlDoc)給我一個[object XMLDocument] – Matthias 2013-02-20 11:01:00

+0

可能是你的'feedback.xml'不在正確的位置。 – yogi 2013-02-20 11:07:50

回答

0

<?xml version="1.0" encoding="ISO-8859-1"?>添加到xml的頂部是我的原始建議。不過,我在Ubuntu上檢查了我的Firefox,並且您的代碼正在工作。我試圖改變編碼,也許這是問題,但事實並非如此。

最初我以爲沒有標題的XML文檔不被Javascript識別爲同一個對象。但再次,在我的Firefox在Firefox中沒有區別,文檔是XMLDocument和列表是HTMLCollection ...

所以真的我很困惑什麼是/是問題。