从文件加载 XML 并解析?

Loading XML from file and parsing?

提问人:Chase Cromwell 提问时间:1/19/2019 最后编辑:Jack BashfordChase Cromwell 更新时间:1/19/2019 访问量:26

问:

我已经搜索了又搜索,但无法弄清楚为什么此代码不会将 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 的新手。

JavaScript jQuery HTML XML 解析

评论

2赞 CertainPerformance 1/19/2019
任何网络或JS错误?
0赞 Chase Cromwell 1/19/2019
没有JS错误,全部通过XAMPP运行。没有控制台错误。
0赞 Yom T. 1/19/2019
您是否尝试在回调中放置断点并检查值?successxml
0赞 Chase Cromwell 1/19/2019
@jom 不太确定我该怎么做?我使用了几个console.logs并得到null和w.fn.init {}

答:

2赞 Jack Bashford 1/19/2019 #1

只需删除该行,它就可以完美运行: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);

现在它运行良好。

评论

0赞 Chase Cromwell 1/19/2019
好悲伤,很简单。谢谢!完美工作!
1赞 Jack Bashford 1/19/2019
没问题!总是乐意帮助@ChaseCromwell
0赞 Chase Cromwell 1/19/2019
已接受时,堆栈会阻止在提出问题后 10 分钟内接受答案。