什么是解析AJAX XML响应的最佳方式 [英] what's the best way to parse xml response in AJAX

查看:93
本文介绍了什么是解析AJAX XML响应的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种反应与XML请求的服务器,我想分析它的JavaScript。我真的很喜欢这个动作XML解析器真的很容易让我使用。我徘徊有一个非常简单/简单的方法来分析,我从服务器获取的XML?

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?

理想的使用情况应该是:

The ideal usage should be:

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

fetchXML new XMLParser. parser.parse access the document.

顺便说一句我打算使用jQuery。

btw I plan to use jquery.

推荐答案

一个普通的 $ AJAX 数据类型:XML会做的伎俩,那么你就可以浏览内容与jQuery选择像你这样一个简单的网页(如本例中的 ATTR 函数来检索 code每本书节点或查找功能查找特定的节点类型)。

A regular $.ajax with 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 attr function in the example to retrieve the "code" field of each book node or the find function to find specific node types).

例如,你可以这样做是为了找到一个特定的书标题:

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

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

其中, XML 成功处理程序接收从 $。AJAX

where xml is the data the success handler receives from $.ajax.

下面是完整的例子:

<!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>

和一个匹配的XML文件:

And a matching XML file:

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

这篇关于什么是解析AJAX XML响应的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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