Reputation: 13843
I'm making a simple ajax call in JavaScript which returns an ID, I then need to make another ajax call to fetch an XML file which contains all of the ID's with the relevant descriptive string as part of the XML.
The ID's description comes back in this format:
<Category>
<Id>1</Id>
<Descriptor>Accounts</Descriptor>
</Category>
<Category>
<Id>2</Id>
<Descriptor>Marketing</Descriptor>
</Category>
<Category>
<Id>3</Id>
<Descriptor>HR</Descriptor>
</Category>
etc...
How can I lookup the ID value against this XML and return the Descriptor string using JavaScript?
Upvotes: 0
Views: 506
Reputation: 318182
With jQuery you could do:
var xml = $.ajax({......}); //your xml
var numb = $.ajax({......}); //returns 1,2 or 3 etc...
var descriptor = $('id', xml).filter(function() {
return $(this).text() == numb; //filter elements based on text in the id tag
}).siblings('Descriptor').text();
jQuery will treat it as html, but it seems to work all the same.
Upvotes: 2
Reputation: 53301
Something like this function should work:
function searchXmlForId(id) {
var searchDescriptor = "";
$.ajax({
type: "GET",
url: "your/xml/file.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Category').each(function(){
if (curId == $(this).find('Id').text()) return $(this).find('Descriptor').text();
});
}
});
return false;
}
And then you call it like this:
var myDescriptorFromId = searchXmlForId(1);
>> "Accounts"
Upvotes: 1
Reputation: 53319
People are going to jump down my throat for suggesting regex here, but I contest that it's probably the fastest solution (for the haters, I'm not parsing xml here, and have no intention to -- I'm simply extracting information via a text pattern):
var matches = xml.match(new RegExp('<Id>' + id + '<\\/Id>[\\s\\S]*?<Descriptor>(.*?)</Descriptor>', 'i'))
var description = matches ? matches[1] : null;
Upvotes: 1