javascript - 从文件加载 XML 并解析?

标签 javascript jquery html xml xml-parsing

我搜索了又搜索,但无法弄清楚为什么这段代码不会将 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/

相关文章:

javascript - YouTube 视频无法加载播放列表

javascript - 将表单数据传递给 python

java - 如何获得包含特定颜色的 CSS 选择器?

foreach php 中的 Javascript - Magento

javascript - 更改屏幕大小时如何将文本保持在 html 部分的中心?

javascript - 添加幻灯片回调以动画 Jquery

javascript - 使用 cell.appendChild 时如何让 <div> 和 <img> 在同一个单元格中?

javascript - 使用 jQuery 进行字符串插值

html - Schema.org 网页 - isPartOf?

javascript - jsTree 创建文件夹 - 在用户输入名称之前创建的文件夹