Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

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 new XMLParser. parser.parse access the document.

btw I plan to use jquery.

like image 977
Bin Chen Avatar asked Oct 18 '10 09:10

Bin Chen


People also ask

How can we retrieve data from XML using AJAX?

Retrieving data from server as XML We will also see how to render that data in the browser. For that, we will create a button on the client side. Once users click on the button, the Ajax script associated will fetch data from an XML file on the server and then it will be rendered in the browser.

What is the use of XML in AJAX?

XML is commonly used as the format for receiving server data, although any format, including plain text, can be used. AJAX is a web browser technology independent of web server software. A user can continue to use the application while the client program requests information from the server in the background.


1 Answers

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']")

where xml is the data the success handler receives from $.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 version="1.0" encoding="UTF-8"?> 
<books title="A list of books">
 <book code="abcdef" />
 <book code="ghijklm">
  Some text contents
 </book>
</books>
like image 196
wildpeaks Avatar answered Oct 19 '22 23:10

wildpeaks