Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse xml response with jQuery

HI all,
I use jQuery to parse my xml responses.

I have this xml :

<?xml version="1.0" encoding="UTF-8"?>
<response status="ok">
  <client_id>185</client_id>
</response>

And i want to get "client_id" value.

like image 491
Shyne Avatar asked Feb 04 '09 11:02

Shyne


People also ask

Does jQuery work with XML?

jQuery can be used for XML processing on the Web as well as HTML processing, and in this article I show some examples of this use.

How do I parse XML in Python?

There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.

What is US XML?

XML stands for extensible markup language. A markup language is a set of codes, or tags, that describes the text in a digital document. The most famous markup language is hypertext markup language (HTML), which is used to format Web pages.


3 Answers

To fix the expected response data type to XML right in your request, set the dataType parameter to "xml". If you don't, jQuery uses the response headers to make a guess.

It is supported on the $.ajax() function as part of the options object, as well as on $.get() and $.post():

jQuery.ajax( options ) jQuery.get( url, data, callback, type ) jQuery.post( url, data, callback, type ) 

So you could do this:

$.ajax({   type: 'GET',   url: "foo.aspx",   data: {     key: "value"   },   dataType: "xml",   success: function (xml){     var clientid = $(xml).find('client_id').first().text();     alert(clientid);   }    }); 

Note that as of jQuery 1.5 you can use a nicer version of the above Ajax request:

$.get("foo.aspx", {   key: "value" }) .done(function (xml){   var clientid = $(xml).find('client_id').first().text();   alert(clientid); }); 
like image 167
Tomalak Avatar answered Oct 14 '22 12:10

Tomalak


First, make a request for the XML with $.get or however you want. Then:

clientID = $(myXML).find("client_id").text(); 
like image 36
Salty Avatar answered Oct 14 '22 13:10

Salty


Use something like this:

$.ajax({ type: 'GET', url: 'test.xml', dataType: 'xml', success: function(xml){
            $('response', xml).each(function() {alert($(this).find('client_id').text());});         
            }});
like image 43
kgiannakakis Avatar answered Oct 14 '22 13:10

kgiannakakis