I'm a js/jquery noob and have been struggling to get an anonymous function to work as a regular function. Could someone point out what I'm doing wrong?
Here's what's taken me a few hours:
var tracklist = new Array();
function stuffXML(xml) {
$(xml).find('track').each(function(){
var logo = $(this).find('logo').text();
var location = $(this).find('location').text();
var id = $(this).find('identifier').text();
var info = $(this).find('info').text();
var title = $(this).find('title').text();
var creator = $(this).find('creator').text();
tracklist.push(logo,location,id,info,title,creator);
});
con开发者_开发问答sole.log('mid' + tracklist); //works here
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "real.xml",
dataType: "xml",
success: stuffXML
});
console.log(tracklist); //but not here - empty array
});
I'm trying to parse the list (a bunch of images & text for a slideshow) into an array (successful there) and then have them available but my scope is clearly too confined. I can't see what I'm doing wrong tho...
Any help would be appreciated...
Your problem is just that you're forgetting what the A in AJAX stands for. Asynchronous. When you run the command for
$.ajax({
type: "GET",
url: "real.xml",
dataType: "xml",
success: stuffXML
});
It runs it immediately, without hesitation, and follows it up immediately with your console.log. In the background, the browser is busy making a request for the data and then adding it to your tracklist variable. So, what you want to do is put that console.log inside of stuffXML. Granted, you probably want to do other things than console.log.. so, have the 'stuffXML' fire off any other events you need to fire to get the rest of your code doing what it needs to do. Just remember that a web server isn't going to serve a request to your page faster than javascript is going to get to the next line of code to execute.
The array is empty there because that code is ran immediately after the DOM is ready, but not necessarily (and extremely unlikely) after the XHR has been completed.
To be able to make use of tracklist
, you will need to refer to it inside the stuffXML()
function or in another function that's stack trace has a stuffXML()
ancestor.
When you call console.log()
in the document-ready function it's unlikely the Ajax request will have completed: the callback happens at the end of the Ajax request; the document ready call will happen immediately after the request has been made.
精彩评论