Teddybugs
Teddybugs

Reputation: 1244

Jquery: Read or parse xml

my xml look like this:

<Container>
<name>x</name>
<id>2</id>
</Container>

to be exact, this is view source of my xml result: xml result

my jquery code:

 $.ajax({
                        type: "post",
                        url: "somefile.jsp",
                        dataType: "xml",
                        success: function(xml) {


                            alert("123:"+xml+":321");


                            },
                        error: function(httpRequest, textStatus, errorThrown) { 
                        alert("status=" + textStatus + ",error=" + errorThrown);

                        }
                        }); 

Question: how do i read it from jquery and assign the name and id to variable?
Problem: the alert return me xml document object

Upvotes: 0

Views: 115

Answers (3)

Priya Gund
Priya Gund

Reputation: 156

Try this one: var container= $xml.find("Container").text(); if var container contains whole xml, then further you can find elements which you want.

Upvotes: 0

megawac
megawac

Reputation: 11373

Setting the dataType property in a jQuery causes the success callback to be called with an xml document. Now just wrap this with jQuery:

success: function(xml) {
    var $xml = $(xml);
    var name = $xml.find('name').text();
    var id = $xml.find('id').text();
    alert("123:"+ id + " " + name +":321"); //alerts "123: 2 x:321")
}

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388446

Since the dataType is xml, the success callback gets a xml document as the result, in order to use jQuery to lookup elements you need to create a jQuery wrapper using $(xml) then you can use jQuery method on the new object as shown below

var $xml =  $(xml)
alert("123:"+$xml.find('name').text()+":321");

Demo: Fiddle

Upvotes: 2

Related Questions