我在使用jquery解析xml时遇到了一些问题。我自己做了一些研究,但是我找不到问题的答案。问题是parseXml函数没有在div中显示任何带有id结果的结果,div信息也没有显示“success”。当我将qanda.xml更改为不存在的文件名如qandaa.xml时,信息div显示“找不到XML文件”所以我认为文件已加载但是parseXml函数出了问题。
XML(qanda.xml)
<?xml version="1.0" encoding="UTF-8"?>
<QandA>
<question>how much?</question>
<answer>100</answer>
</QandA>
<QandA>
<question>how much?</question>
<answer>110</answer>
</QandA>
<QandA>
<question>how much?</question>
<answer>120</answer>
</QandA>
<QandA>
<question>how much?</question>
<answer>130</answer>
</QandA>
<QandA>
<question>how much?</question>
<answer>140</answer>
</QandA>
html页面
<!DOCTYPE HTML>
<html>
<head>
<LINK REL=StyleSheet HREF="layout.css" TYPE="text/css" MEDIA=screen>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var information = $("#info");
var result = $("#result");
$.ajax({
type: "GET",
url: "qanda.xml",
datatype: "xml",
success: parseXml,
error: function(xhr, status, error) {
if(xhr.status==404) {
information.text("XML file not found");
}
}
});
function parseXml(xml) {
$(xml).find('QandA').each(function(){
result.append($(this).find('question').text());
result.append($(this).find('answer').text());
});
information.text("Success");
}
});
</script>
</head>
<body>
<div id="info"></div>
<div id="result"></div>
</body>
</html>
答案 0 :(得分:1)
认为您的XML需要一个根元素。
>>> str = '<?xml version="1.0" encoding="UTF-8"?><root><a></a></root>'
"<?xml version="1.0" encoding="UTF-8"?><root><a></a></root>"
>>> $(str).find("a")
Object[a]
和
>>> str = '<?xml version="1.0" encoding="UTF-8"?><a></a>'
"<?xml version="1.0" encoding="UTF-8"?><a></a>"
>>> $(str).find("a")
Object[]