【问题标题】:Loading XML from file and parsing?从文件加载 XML 并解析?
【发布时间】:2019-06-13 08:33:21
【问题描述】:

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

【问题讨论】:

  • 任何网络或 JS 错误?
  • 没有 JS 错误,都是通过 XAMPP 运行的。没有控制台错误。
  • 您是否尝试在success 回调中放置断点并检查xml 值?
  • @jom 不太清楚我会怎么做?我已经使用了几个 console.logs 并得到 null 和 w.fn.init {}

标签: javascript jquery html xml xml-parsing


【解决方案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);

现在它可以完美运行了。

【讨论】:

  • 好悲痛,这很简单。谢谢!完美运行!
  • 没问题!总是很高兴帮助@ChaseCromwell
  • 接受,Stack 阻止在提出问题后 10 分钟内接受答案。
猜你喜欢
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-14
相关资源
最近更新 更多