Reputation: 2680
I'm loading data from an XML hierarchy using ajax. First I load the parent file, then I loop through all nodes and loads another XML file for each node. I want to place the result from all these XML load's into a java object, then do something.
Here is the code:
$(document).ready(function(){
$.when(getXmlFile('ansatt',request('meglerid'),writeEmployee)).done();
});
var items;
function writeEmployee(data){
var def = [];
_.each(data.children[0].children,function(item,key,list){
//Get more data about each property
var propid = findField(item,'oppdragsnummer');
def.push(getXmlFile('oppdrag',propid,writeProperty));
});
$.when(def).done(function(){console.log('loaded ' + items.length)});
}
function writeProperty(data){
items.push(data);
}
function getXmlFile (type,id, func){
return $.ajax({
type: "GET",
contentType: "application/xml",
url: "http://privatmeglerdrammen.no.er3.itum.com/site/privatmeglerdrammen.no/design/renderings/xml/" + type + id + ".xml",
dataType: "xml"
}).done(function (data){
func(data);
});
}
When all is said and done, the items array contains 119 elements, but the console.log('loaded ..') line outputs 0 elements.
What am I doing wrong?
Upvotes: 0
Views: 47
Reputation: 8205
If you take a look at the documentation for when there's this line (em mine):
If a single argument is passed to
jQuery.when()
and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.
You're passing an array of jqXHR objects. If you pass them one at a time, you'll get the logging you expect.
For example, using Function.apply
:
$.when.apply($, def).done(function() {/* insert logging */});
Upvotes: 1
Reputation: 10786
You can use ajaxStop() to run a function when all ajax calls are done: https://api.jquery.com/ajaxStop/
$(document).ajaxStop(function() {
DoSomething();
});
Upvotes: 1