Javascript - Getting data from XML for later use... put in array or object?
I am extracting a bunch of data from an XML file using jQuery. I need to use the data to fill in image paths, names, etc.
What is the best way to gather all of this data for use? For instance, I get everything like so:
$(document).ready(function() {
$.ajax({
type: "GET",
url:开发者_如何学运维 "stuff.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('speaker').each(function(){
var img_path = $(this).find('speaker_image').text();
var name_text = $(this).find('speaker_name').text();
// should I build an array or object here?
});
}
});
});
Should I stick everything into an array in the success method? Maybe in an object? What I will do is take the collected data and use it to build a list of names and images. There will be quite a few elements in this and it will look something like (with img_path
being used in the image url and name_text
being used for the label:
<ul>
<li><img src="images/bobsmith.jpg" /><br /><lable>Bob S. Smith</label></li>
<li><img src="images/crystalforehead.jpg" /><br /><lable>Crystal X. Forehead</label></li>
...
</ul>
What is the best way to handle the collected data so I can go through and build the html I need using it?
If you do not need to re-use the data from the XML file, why not build the DOM elements whilst you are reading it?
So for example in your success method:
$(xml).find('speaker').each(function(){
var img_path = $(this).find('speaker_image').text();
var name_text = $(this).find('speaker_name').text();
var html = '<li><img src="' + img_path + '" /><br /><label>' + name_text + '</label></li>';
$("#myList").append(html);
});
This will put the retrieved results in an array using push
:
success: function(xml) {
var results = [];
$(xml).find('speaker').each(function(){
results.push($(this));
});
Put it into an array object if you need to re-use:
function linkItem(linkImage, linkText)
{
this.linkImage = linkImage;
this.linkText = linkText;
};
function mylist()
this.speakerList = new Array();
$(xml).find('speaker').each(function()
{
this.speakerList [$(this).index()] = new linkItem($(this).find('speaker_image').text(), $(this).find('speaker_name').text());
};
};
Just build it if you use only once:
var myhtml = ""
$(xml).find('speaker').each(function(){
myhtml = myhtml + '<li><img src="' + $(this).find('speaker_image').text() + '" /><br /><label>' + $(this).find('speaker_name').text() + '</label></li>';
});
then use it:
$(selector).append(myhtml);
or
$(selector).innerHtml(myhtml);
精彩评论