我搜索了又搜索,但无法弄清楚为什么这段代码不会将 XML 元素加载到
中。我正在尝试从文件加载 XML,读取特定元素并将其数据放入特定元素。
HTML:
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET" ,
url: "score1.xml" ,
dataType: "xml" ,
success: function(xml) {
var xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc );
$home = $xml.find( "home" );
$( "#home" ).text( $home.text() );
}
});
});
</script>
</head>
<body><p id="home"></p>
</body>
</html>
score1.xml
:
<?xml version="1.0" encoding="UTF-8"?><score><home>22</home></score>
(还应该补充一点,虽然我多年来一直使用 PHP/HTML,但我完全是 OOP 和 JQuery 的新手。)
最佳答案
只需删除 parseXML
行即可完美运行:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "score1.xml",
dataType: "xml",
success: function(xml) {
var $xml = $(xml);
$home = $xml.find("home");
$("#home").text($home.text());
}
});
});
我已经删除了这一行:
var xmlDoc = $.parseXML(xml);
现在它完美地工作了。
关于javascript - 从文件加载 XML 并解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54264783/