2011-03-08 41 views
0

我使用這個代碼:爲什麼這個javascript代碼不能處理這個xml文件?

<script type="text/javascript"> 
if (window.XMLHttpRequest) 
{ 
xmlhttp=new XMLHttpRequest(); 
} 
else 
{ 
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
} 
xmlhttp.open("GET","css/galerii.xml",false) 
xmlhttp.send(); 
xmlDoc=xmlhttp.responseXML; 
alert(xmlDoc.getElementsByTagName("GALERIE")[0].childNodes[0].nodeValue); 
</script> 

處理一些XML:

<?xml version="1.0" encoding="UTF-8" ?> 
<GALERIES> 
<GALERIE> 
info 
</GALERIE> 

<GALERIE> 
other info 
</GALERIE> 
</GALERIES> 

但我在警報得到什麼,不應該xmlhttp.open( 「GET」,「CSS/galerii.xml「,false)如果成功則有值嗎?它沒有定義。 現在有一個根節點,結果相同。

回答

2

您沒有根節點(文檔元素),這是XML中的一項要求。

<?xml version="1.0" encoding="UTF-8" ?> 
<GALERIES> 
    <GALERIE> 
    info 
    </GALERIE> 

    <GALERIE> 
    other info 
    </GALERIE> 
</GALERIES> 

對於您的AJAX請求,您也沒有onreadystatechange方法。當讀取responeXML的代碼執行時,XML的http請求尚未返回。您需要關於如何構建AJAX請求讀了起來:https://developer.mozilla.org/en/xmlhttprequest

工作例如:http://jsfiddle.net/2F8q6/1/

你的JS修改工作的例子做:

<script type="text/javascript"> 
    if (window.XMLHttpRequest) 
    { 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    { 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.open("GET","css/galerii.xml", false); 

    xmlhttp.onreadystatechange = function() 
    { 
     if(xmlhttp.readyState === 4 && xmlhttp.status === 200) 
     { 
      xmlDoc=xmlhttp.responseXML; 
      alert(xmlDoc.getElementsByTagName("GALERIE")[0].childNodes[0].nodeValue); 
     } 
    } 

    xmlhttp.send(); 
</script> 
+0

即使有根節點,我也得到了相同的結果。 – Kesarion 2011-03-08 18:09:50

+0

看到我編輯的答覆 – JAAulde 2011-03-08 18:48:57

+0

謝謝你的答案。我在這個腳本中創建了一個新頁面,並且我什麼也得不到。什麼可能是錯的。順便說一句,不應該xmlhttp.open(「GET」,「css/galerii.xml」,false);作爲第三個參數有效嗎?我嘗試了兩種方式,但仍然沒有。 – Kesarion 2011-03-08 19:20:49

1

XML文檔可能只有一個根元素。

1

你需要一個根元素。

<?xml version="1.0" encoding="UTF-8" ?> 
<GALERIES> 
    <GALERIE> 
    info 
    </GALERIE> 
    <GALERIE> 
    other info 
    </GALERIE> 
</GALERIES>