Can Javascript directly handle an xml file requested via AJAX. I have a server side xml file and need to populate fields from this xml. Can i say 'directly read "xmlfile.xml" (on server)' and then extract values in javascript from the response received and populate as required? Can you explain with example if possible?
If you can use jQuery, you can simply perform an XML
AJAX call, and respond with the static file.
<script type="application/javascript">
$(function() {
$('#get-xml a').click(function() {
$.ajax({
type: "GET",
url: "xmlfile.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('label').each(function(){
// your code. some example code bellow
var id_text = $(this).attr('id')
var name_text = $(this).find('name').text()
$('<li></li>')
.html(name_text + ' (' + id_text + ')')
.appendTo('#get-xml ol');
});
}
});
});
});
</script>
Just be carefull:
Note: If you specify the dataType option described below, make sure the server sends the correct MIME type in the response (eg. xml as "text/xml"). Sending the wrong MIME type can lead to unexpected problems in your script.
As is the standard here on SO, I'm going to recommend using jQuery!
var myUrl = 'http://somesite.com/foo.xml';
function myXmlHandler(data){
// do stuff with data, which is the contents of foo.xml
}
$.get(myUrl,{},myXmlHandler);
Yes. XMLHttpRequest has a responseXML
property (populated once the request is completed in the usual way) which is a reference to an XML document. This has all the usual DOM methods and properties that you'd get in an HTML document. You do not need 50K of jQuery to achieve this.