I recent problem i had was just how to parse xml returned by ajax.
I know a few of you will scream JSON at me but i have done quite a bit using ajax and xml in the past so there;-).
You can use standard javascript for this(as i have) but as ever jQuery provide tools to do the same functions in just a few lines. When you need to RAD this is very helpful.
So first off lets see how JQuery handles an xmlDocument below.
<root> <clients> <client id="1"> <surname>Kat</surname> <forename>The</forename> </client> <client id="2"> <surname>Kat2</surname> <forename>The</forename> </client> </clients> </root>
The first thing to do is cast the xmlDocument to a jQuery object.
var jXML = $(xml);
Now to select elements we can use the .find() method.
This really is where jQuery excels. simply put .find(name) will find all element(s) named name.
var clients = $(jXML).find('client');
Notice we can bypass the clients element and go straight to client. We could also just get all surnames in a similar way.
Now to access the properties we either use .attr() method for attributes or the .text() method for text contents.
$(clients).each(function() { alert($(this).attr('id')); });
// would give alert 1 and alert 2
$(clients).each(function() { alert($(this).find('surname').text()); });
// would give alert Kat and alert Kat2
So lets add it all together with the marvellous $.ajax() method.
function retrieveClients(){
$.ajax({
url: "retrieveClients.html",
cache: false,
type: "GET",
dataType: "xml",
success: function(xml){ $(xml).find('client').each(function(){
alert($(this).find('forename').text() );
alert($(this).find('surname').text() );
});
}
});
};
|