Na wszelki wypadek przydaje się każdemu, kto może spotkać się z tym —, a dzięki zaliczkom promesy w jQuery — T.J. Odpowiedź Crowder można teraz poprawiła w jeden zwięzły i ogólną funkcję:
/**
* Load multiple JSON files.
*
* Example usage:
*
* jQuery.getMultipleJSON('file1.json', 'file2.json')
* .fail(function(jqxhr, textStatus, error){})
* .done(function(file1, file2){})
* ;
*/
jQuery.getMultipleJSON = function(){
return jQuery.when.apply(jQuery, jQuery.map(arguments, function(jsonfile){
return jQuery.getJSON(jsonfile);
})).then(function(){
var def = jQuery.Deferred();
return def.resolve.apply(def, jQuery.map(arguments, function(response){
return response[0];
}));
});
};
Jednak chodzi o nie podając żadnych informacji zwrotnej do użytkownika — podczas oczekiwania na pełnym obciążeniu — jest dobry. Tak więc dla tych, którzy wolą udzielać responsywnych informacji zwrotnych, oto nieco bardziej skomplikowana wersja, która obsługuje postęp.
/**
* Load multiple json files, with progress.
*
* Example usage:
*
* jQuery.getMultipleJSON('file1.json', 'file2.json')
* .progress(function(percent, count, total){})
* .fail(function(jqxhr, textStatus, error){})
* .done(function(file1, file2){})
* ;
*/
jQuery.getMultipleJSON = function(){
var
num = 0,
def = jQuery.Deferred(),
map = jQuery.map(arguments, function(jsonfile){
return jQuery.getJSON(jsonfile).then(function(){
def.notify(1/map.length * ++num, num, map.length);
return arguments;
});
})
;
jQuery.when.apply(jQuery, map)
.fail(function(){ def.rejectWith(def, arguments); })
.done(function(){
def.resolveWith(def, jQuery.map(arguments, function(response){
return response[0];
}));
})
;
return def;
};
'daataUrls' wydaje się być niezdefiniowany. – Utkanos
Tak, jest symbolem zastępczym, aby inni zrozumieli, co chcę osiągnąć. –