I am trying to write a jQuery plugin and read through some XML, but I don't seem to be getting any return values. The xml seem to be coming back ok if I just console.log using debugging tool, but it doesn't seem to be parsing. I tried different parsing method, but doesn't seem to be outputting.
JavaScript Code
;(function ($) {
/**
* Plugin Definition
*/
$.fn.extend({
feedr: function (option) {
var result;
var $this = this;
$.ajax({
type: 'GET',
url: 'feedr.xml',
dataType: 'xml'
})
.done(function (xml) {
var xmlDocument = $.parseXML(xml);
var $xml = $(xmlDocument);
var $type = $xml.find('type');
return $this.html($type.text());
});
}
});
}(jQuery));
XML File
<?xml version="1.0" encoding="UTF-8" ?>
<feedr>
<feed>
<type>rdf</type>
<uri>ABC</uri>
</feed>
<feed>
<type>rdf</type>
<uri>ABC</uri>
</feed>
<feed>
<type>rss</type>
<uri>DEF</uri>
</feed>
</feedr>
HTML File
<!DOCTYPE html>
<html lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="feedr/js/jquery-feedr.js"></script>
<script type="text/javascript">
$(function () {
$('.feedr').feedr();
});
</script>
</head>
<body>
<div id="feedr" class="feedr" data-xml="feedr"></div>
</body>
</html>
To fix change your done() to this:
.done(function (xml) {
var $xml = $(xml);
var $type = $xml.find('type');
return $this.html($type.text());
});
The reason is that the ajax call specifies that the content coming back is XML so jQuery pre-parses it and hands it to done as an XML document, not a string.
So, you are trying to turn a document into a document, the action fails and returns null.
Here's a fiddle that may help you - http://jsfiddle.net/XjDfp/