jQuery 在 AJAX 中解析 xml 响应的最佳方法是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3957932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:24:59  来源:igfitidea点击:

what's the best way to parse xml response in AJAX

jqueryxmlajax

提问by Bin Chen

I have a server that response the request with XML, I want to parse it in the javascript. I really like the actionscript xml parser that is really easy for me to use. I am wandering is there a very easy/straightforward way to parse the XML I fetched from server?

我有一个用 XML 响应请求的服务器,我想在 javascript 中解析它。我真的很喜欢 actionscript xml 解析器,它对我来说真的很容易使用。我在徘徊是否有一种非常简单/直接的方法来解析我从服务器获取的 XML?

The ideal usage should be:

理想的用法应该是:

fetchXML new XMLParser. parser.parse access the document.

fetchXML 新的 XMLParser。parser.parse 访问文件。

btw I plan to use jquery.

顺便说一句,我打算使用 jquery。

回答by wildpeaks

A regular $.ajaxwith dataType: "xml"will do the trick, then you can browse the contents with jQuery selectors like you would a simple web page (e.g. the attrfunction in the example to retrieve the "code" field of each book node or the findfunction to find specific node types).

一个普通的$.ajaxwithdataType: "xml"可以解决这个问题,然后你可以像浏览一个简单的网页一样使用 jQuery 选择器浏览内容(例如attr,示例中的函数检索每个书节点的“代码”字段或find查找特定节点类型的函数)。

For example, you could do this to find a specific book by title:

例如,您可以这样做以按标题查找特定书籍:

$(xml).find("book[title='Cinderella']")

where xmlis the data the successhandler receives from $.ajax.

处理程序从哪里接收到xml的数据。success$.ajax



Here is the complete example:

这是完整的示例:

<!DOCTYPE html>
<html>
<head>
 <title>jQuery and XML</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <meta name="language" content="en" />
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body

<div id="output"></div>

<script type="text/javascript">
$(document).ready(function(){
 $.ajax({
  type: "GET",
  dataType: "xml",
  url: "example.xml",
  success: function(xml){
   $(xml).find("book").each(function(){
    $("#output").append($(this).attr("code") + "<br />");
   });
  }
 });
});
</script>


</body>
</html>

And a matching XML file:

还有一个匹配的 XML 文件:

<?xml version="1.0" encoding="UTF-8"?> 
<books title="A list of books">
 <book code="abcdef" />
 <book code="ghijklm">
  Some text contents
 </book>
</books>

回答by Quentin

Return the data with the right content type (e.g. application/xml) and XHR will parse it for you.

返回具有正确内容类型(例如application/xml)的数据,XHR 将为您解析它。

See also: the dataType argument for jQuery's ajax method.

另请参阅:jQuery 的ajax 方法的 dataType 参数。