Creating an JavaScript array of objects from an XML source
I am successfully creat开发者_如何学Pythoning objects from some XML. I am then attempting to put each new object into a a new index of an array which will end up containing all the objects.
However, the array keeps returning as empty. My code follows:
var $locations = [];
/*$obj = {};
$obj['test'] = 'working';
$locations.push($obj);*/
$.ajax({
type: "POST",
url: "/locations/845/data.xml",
dataType: "xml",
success: function($xml){
$($xml).find('node').each(
function(){
$location = {};
//alert( $(this).attr('Latitude') );
$location['latitude'] = $(this).attr('Latitude');
$location['longitude'] = $(this).attr('Longitude');
$location['city'] = $(this).attr('City');
$location['street'] = $(this).attr('Street');
//alert( $location.toSource() );
//alert( $location['latitude'] );
$locations.push($location);
}
);
}
});
alert( $locations.toSource() );
The commented object created and inserted into the $locations array is a test and it works. But the actual useful code within the ajax success function does not.
Your ajax call is asynchronous. When you call it, that just starts the execution of it and the rest of your code continues to run. The ajax has not completed yet when your alert fires and it is not complete until the success handler function is called. The ONLY place you can know that the ajax call is complete is in the success handler itself. In fact anything you want to do with the ajax data that is returned should be initiated from the success handler, not from code that executes after you've called the ajax call.
If you move the line:
alert( $locations.toSource() );
to the end of the success handler function, then you will see your data. Only then has the ajax call actually completed.
Try it like this:
var $locations = [];
/*$obj = {};
$obj['test'] = 'working';
$locations.push($obj);*/
$.ajax({
type: "POST",
url: "/locations/845/data.xml",
dataType: "xml",
success: function($xml){
$($xml).find('node').each(
function(){
$location = {};
//alert( $(this).attr('Latitude') );
$location['latitude'] = $(this).attr('Latitude');
$location['longitude'] = $(this).attr('Longitude');
$location['city'] = $(this).attr('City');
$location['street'] = $(this).attr('Street');
//alert( $location.toSource() );
//alert( $location['latitude'] );
$locations.push($location);
}
);
alert( $locations.toSource() );
}
});
精彩评论