Chỉ trong trường hợp nó hữu ích đối với bất kỳ ai khác có thể gặp phải số này — và nhờ lời hứa Hứa hẹn trong jQuery — T.J. câu trả lời Crowder của bây giờ có thể được cải thiện thành một chức năng ngắn gọn và tổng quát:
/**
* 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];
}));
});
};
Tuy nhiên điểm về việc không đưa ra bất kỳ thông tin phản hồi cho người dùng — trong khi chờ đợi đầy tải — là một tốt nhất. Vì vậy, đối với những người thích cung cấp phản hồi phản hồi, đây là phiên bản hơi phức tạp hơn hỗ trợ tiến trình.
/**
* 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' dường như không xác định. – Utkanos
Có, là trình giữ chỗ để làm cho người khác hiểu những gì tôi muốn hoàn thành –