非常簡單的代碼:解析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不會引發任何錯誤。
您是否檢查過XML是否真的返回? – Sirko 2013-02-20 10:59:52
alert(xmlDoc)給我一個[object XMLDocument] – Matthias 2013-02-20 11:01:00
可能是你的'feedback.xml'不在正確的位置。 – yogi 2013-02-20 11:07:50