Jquery - 无法获取检索到的 xml 文件以填充 DOM

Jquery - Couldn't get the retrieved xml file to populate the DOM

本文关键字:文件 xml 填充 DOM 获取 检索 Jquery      更新时间:2023-09-26

我正在尝试检索一个 xml 文件,并在页面上显示内容,但到目前为止我无法让它工作。我可以确认文件已成功检索,因为我在网络捕获上获得了 200。我尝试为$title放置一个警报框,但它是空白的。

我不知道我在这里做错了什么。任何帮助将不胜感激。谢谢

下面是我的标记

<div id="textArea">This is a test</div>

我的脚本.js

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "BooksCatalog.xml",
        dataType: "xml",
        success: function (result) {
            var xmlDoc = $.parseXML(result),
            $xml = $(xmlDoc),
            $title = $xml.find("title");
            $("#textArea").append($title.text());        
        }
    });
});

图书目录.xml

<?xml version="1.0" encoding="utf-8" ?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>
      An in-depth look at creating applications
      with XML.
    </description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>
      A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.
    </description>
  </book>
</catalog>

我相信问题是对parseXML的调用。 jQuery应该已经返回了解析的结果,所以此步骤不是必需的,并且可能会导致问题。尝试将其注释掉,然后简单地调用

$("#textArea").append($(result).find('title'));