【问题标题】:counting the number of nodes is not working计算节点数不起作用
【发布时间】:2012-07-07 07:12:58
【问题描述】:

我有一个 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;

【问题讨论】:

  • 强烈建议进行同步 ajax 请求(false 作为open 的第三个参数使其同步);改用 asynchronous 请求和 onreadystatechangehandler 回调。同步 ajax 请求会导致糟糕的用户体验。

标签: javascript xml xml-parsing


【解决方案1】:

两个可能的答案:

A) XML 有错误,你有&lt;/phone&gt;,你需要&lt;/city&gt;。所以你需要解决这个问题。 :-)(但我猜这只是问题,而不是你的真实数据,因为如果它在你的真实数据中,你就不会得到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

【讨论】:

    猜你喜欢
    • 2013-05-01
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    相关资源
    最近更新 更多