gpt4 book ai didi

javascript - 计算节点数不起作用

转载 作者:行者123 更新时间:2023-11-28 09:48:51 25 4
gpt4 key购买 nike

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

最佳答案

两个可能的答案:

A) XML 有错误,您有 </phone>您需要的地方</city> 。所以你需要解决这个问题。 :-)(但我猜这只是在问题中,而不是在您的真实数据中,因为如果它在您的真实数据中,您将不会得到 0 ,我不认为;您会得到一个错误。)

B) 检查您的响应 header ,您的服务器可能未返回具有正确 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

关于javascript - 计算节点数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11373062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com