Getting root node attribute, jQuery/XML
this is probably so trivial that I'm ashamed to be asking this...
Why in the world is this not working?
<?xml version="1.0" encoding="UTF-8"?>
<filter id="4" max_values="10">
<value id="9">strategy</value>
<value id="11">simulation</value>
<value id="12">shooter</value>
</filter>
This is the xml response I get when I request the page with:
$.post('afilters/getvaluesXml', {filter_id: fid},
function(response){
var fields;
alert(response);
var filter_id = $(response).find('filter').attr('id');
var max_values = parseInt($(response).find('filter').attr('max_values'));
alert('filter_id: '+filter_id+' max_values:'+max_values);
$(response).find('value').each(function(){
var id = $(this).attr('id');
var value = $(this).text();
if(max_values == 1){
fields = fields+'<input type="radio" name="'+filter_id+'" value="'+id+'"/>'+value+'<br/>';
} else {
fields = fields+'<input type="checkbox" name="'+filter_id+'[]" value="'+id+'"/>'+value+'<br/>';
}
});
//alert(fields);
$('#'+filter_id+'_values').text(fields);
});
Everything works fine开发者_开发问答 except I am unable to get the filter_id and max_values attributes. This is the alert box content:
filter_id: null max_values:NaN
And, why when I specify the datatype "xml" as described in the jquery .post() docu, nothing gets back to me (no response is ever received - callback is never executed).
I have tried setting dataType to xml and it worked like a charm, have a look at this snippet:
$.post('afilters/getvaluesXml', {filter_id: fid}, function(response){
var filter_id = $('filter', response).attr('id');
var max_values = parseInt($('filter', response).attr('max_values'));
alert('filter_id: '+filter_id+' max_values:'+max_values);
}, 'xml');
Damn... Well you are all right. It is just me who forgot to set the proper header before outputting the xml...
So setting the output header to "content-type: text/xml" entirely fixed this problem.
Seems jQuery won't execute the callback when the content type is not as expected.
It is however weird that everything apart those two root node attributes worked :)
Thank you for pointing me in the right direction.
Maybe not the best practice but it works
var filter_id = $(response).find("value:first").parent().attr('id');
var max_values = $(response).find("value:first").parent().attr('max_values');
精彩评论