为什么这个javascript代码没有处理这个xml文件?

时间:2011-03-08 17:58:40

标签: 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)是否应该有值?这是未定义的。 现在有一个根节点,结果相同。

4 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

XML文档可能只有一个根元素。

答案 2 :(得分:1)

您需要一个根元素。

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

答案 3 :(得分:0)

修复你的xml。你的xml无效。你的xml中没有root元素。 试试这里 http://www.w3schools.com/Dom/dom_validate.asp

相关问题