是否可以使用 jQuery 的 $(responseXML) 语法可靠地解析 XML? [英] Can XML be parsed reliably using jQuery's $(responseXML) syntax?

查看:25
本文介绍了是否可以使用 jQuery 的 $(responseXML) 语法可靠地解析 XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在寻找一种使用 JavaScript 从服务器 XML 响应中提取信息的简单方法.jQuery 似乎是一个很好的候选者.

I'm currently looking for an easy way to extract information from server XML responses using JavaScript. jQuery seems like a good candidate for this.

在使用 jQuery 解析 XML 时,我不断遇到类似于以下代码段的代码示例:

When it comes to parsing XML with jQuery, I keep coming across code examples similar to the following snippet:

function parseXml(responseXml) {

    $(responseXml).find('someSelector')...

}

然而,jQuery Core 文档(下面的引用)明确指出您不应该这样做:

Yet, the jQuery Core documentation (quotation below) clearly states that you aren't supposed to do that:

jQuery( html, [ ownerDocument ] )

html 动态创建的 HTML 字符串.请注意,这会解析 HTML,不是 XML.

html A string of HTML to create on the fly. Note that this parses HTML, not XML.

http://api.jquery.com/jQuery/#jQuery2

这让我想知道为什么这么多在线资源仍然建议通过 $(responseXml) 解析 XML.尽管 API 文档是这样说的,这通常没有任何问题吗?在什么情况下,像这样解析 XML 实际上工作?

This makes me wonder why so many online resources nevertheless suggest parsing XML via $(responseXml). Does this generally work without any problems, despite what the API documentation says? In what cases will parsing XML like this actually not work?

推荐答案

jQuery ajax 文档添加了 http://api.jquery.com/jQuery.ajax/:

the jQuery ajax documentation adds http://api.jquery.com/jQuery.ajax/:

数据类型

xml":返回一个可以通过 jQuery 处理的 XML 文档.

"xml": Returns a XML document that can be processed via jQuery.

...如果服务器将返回数据报告为 XML,则可以使用普通的 XML 方法或 jQuery 的选择器遍历结果...

...If the server reports the return data as XML, the result can be traversed using normal XML methods or jQuery's selectors...

也在 http://api.jquery.com/jQuery/

当从 Ajax 调用返回 XML 数据时,我们可以使用 $() 函数将它包装在一个我们可以轻松使用的 jQuery 对象中.完成此操作后,我们可以使用 .find() 和其他 DOM 遍历方法检索 XML 结构的各个元素.

When XML data is returned from an Ajax call, we can use the $() function to wrap it in a jQuery object that we can easily work with. Once this is done, we can retrieve individual elements of the XML structure using .find() and other DOM traversal methods.

这篇关于是否可以使用 jQuery 的 $(responseXML) 语法可靠地解析 XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆