2012-07-07 77 views
1

我有一個XML文件:計數節點的數量不工作

<?xml version="1.0" encoding="ISO-8859-1"?> 
<food> 
    <cuisine type="Chinese"> 
     <restaurant name = "Panda Express"> 
      <location id= "0"></location> 
      <phone id = "1"></phone> 
      <city id="2"></phone> 
     </restaurant> 
     <restaurant name = "Mr. Chau's"> 

     </restaurant> 
    </cuisine> 
    <cuisine type="Indian"> 
     <restaurant name = "Shan"> 

     </restaurant> 
    </cuisine> 
</food> 

,我試圖來算這個美食節點的數量是我的代碼,我知道它基本上是正確的,但是當我嘗試打印出它說,它的0

//starts talking to the xml document 
     if(window.XMLHttpRequest){ 
      xmlhttp = new XMLHttpRequest(); 
     }else{ 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     xmlhttp.open("GET","data.xml", false); 
     xmlhttp.send(); 
     xmlData = xmlhttp.responseXML; 


     //fills the first comboBox 
     var sel = document.getElementById('CuisineList'); 
     cuisineList = xmlData.getElementsByTagName('cuisine'); 
     document.getElementById("test").innerHTML = cuisineList.length; 
+0

強烈建議**不要**做同步ajax請求(即'false'作爲'open'的第三個參數使其同步);改爲使用*異步*請求和'onreadystatechangehandler'回調。同步ajax請求會導致糟糕的用戶體驗。 – 2012-07-07 07:40:12

回答

0

兩個可能的答案的節點列表的長度:

A)的XML有一個錯誤,你有</phone>,你需要</city>。所以你需要解決這個問題。 :-)(但是我猜這只是在問題中,而不是在你的真實數據中,因爲如果它在你的真實數據中,你不會得到0,我不會想到;你會得到一個錯誤)

B)檢查你的響應標題,可能是你的服務器沒有返回正確的MIME類型的XML。如果不是:

  1. 最好的答案是糾正服務器配置,以便它正確地爲XML文件提供服務。

  2. 如果因任何原因,你不能做到這一點,你可以用overrideMimeType迫使XMLHttpRequest對待響應爲XML:

    xmlhttp.open("GET","data.xml", false); 
    xmlhttp.overrideMimeType("text/xml"); // <=== The new bit 
    xmlhttp.send(); 
    xmlData = xmlhttp.responseXML; 
    

如果你解決這些,它的工作原理:Live working copy | source

+0

感謝工作:) – Ameya 2012-07-07 07:45:57