gpt4 book ai didi

javascript - 使用 jQuery 加载 xml 文件

转载 作者:行者123 更新时间:2023-12-03 07:36:43 25 4
gpt4 key购买 nike

我已经浏览 stackoverflow 一段时间了,但没有找到适合我的问题的答案 - 我想在单击按钮时加载 xml 文件的特定部分。我想将 xml 文件的部分内容加载到“contents”div 中。

这是我的 HTML 代码:

<div>
<input type="button" id="click"/>
<div id="content">

</div>
</div>

这是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<books>
<book id="jeff">
<author>Jeffrey </author>
<title>Books 1</title>
</book>
<book id="jerry">
<author>Jerry</author>
<title>Books 2</title>
</book>
<book id="jimmy">
<author>Jimmy</author>
<title>Boks 3</title>
</book>
<book id="jem">
<author>Jem</author>
<title>Books 4</title>
</book>
</books>

我已经尝试过这个(我知道这是不对的 - 所以请不要讨厌):

$(document).ready(function() {
$('#click').click(function(){
$.ajax({
url : 'books.xml',
dataType : 'xml',
success : parse,
});

function parse(xml){
$('#content').append($(xml).find('authour').text());
}
});
});

我如何使用 jQuery 访问每个作者 id 规范。 (抱歉,如果我搞砸了解释!:))。

最佳答案

可以使用 jQuery 加载 xml $.ajax , $.get , $.post 。一旦你使用 jQuery,它就会有一个方法 $.parseXML :

$.ajax({url: 'file.xml', method: 'GET', dataType: 'xml'}).done(function (xml) {
var xmlDoc = $.parseXML( xml );
var author = $(xmlDoc).find('book[id="jem"]').find('author');
$('#content').append('<span>' + author.text() + '</span>');
});

在本例中,服务器应使用正确的 mime 类型进行响应 Content-type: "text/xml"

关于javascript - 使用 jQuery 加载 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35580272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com