How should I put this XML object into a javascript dictionary?
XMLcoming in from get_objectives.php:
<container>
<objective>
<id>1</id>
<type>thing</type>
<name>banana</name>
<date_added>2012-05-08 21:13:01</date_added>
<released>2012-05-08 22:47:27</released>
</objective>
<objective>
<id>2</id>
<type>thing</type>
<name>hammock</name>
<date_added>2012-05-08 21:13:01</date_added>
<released>2012-05-08 22:47:27</released>
</objective>
</container>
The javascript that doesn’t work, that I”m trying to fix:
function updateObjectives(){
$.post('scripts/get_objectives.php', {}, function(xml){
$(xml).find("objective").each(function(i){
objectives[i] = {}
objectives[i]['id'] = $('id', xml).text()
console.log("objectives["+i+"].id = "+objectives[i].id)
})
})
}
Based on the console output below, it appears that the $('id', xml).text() call that I am trying isn’t stuck inside the function handling the find(“objective”).each call:
objectives[0].id = 12
objectives[1].id = 12
objectives[i]['id'] = $('id', this).text()does the trick!My problem was the ambigious syntax of the
$()in the tutorial;$(query, context). Instead of looking for('this > id', xml)which is looking for ‘this”s child named ‘id’ inside the full ‘xml’ file, (I already had found ‘this’!) so$('id', this)works because it is looking for ‘id’ inside ‘this’ (where ‘this’ is tags) I hope this helps someone!