我想做 AJAX 请求以遵循树状结构,有点像文件系统目录,其中目录链接到其他目录。只有在我的情况下,我才遵循我遵循 ID 的 REST API。就像每个请求一样,我都会收到一个子目录的 ID 列表(最后是“文件”)。
所以我想做的是使用 forEach 在 AJAX 调用中进行 AJAX 调用。我想检查是否发生了错误,并且我想确保它等待请求完成,以便最终我能够处理并返回我收到的数据。我该怎么做?
所以我基本上有这样的 JSON 并从 /directories 开始。我想获取所有文件并将它们作为一个大 JSON 从函数返回。
/目录
["directoryA", "directoryB"]
/目录/目录A
["subDirectory1", "subDirectory2"]
/目录/目录B
["subDirectory4"]
/目录/子目录1
["fileA", "fileB"]
/目录/子目录2
["fileC"]
/文件/文件A
{"some content"}
/文件/文件B
{"Hello world"}
/文件/文件C
{"nickname": "Clown", "id": 9247234}
...
我目前关于这个的代码(对不起,原来的代码是 CoffeeScript 并且做了很多其他的事情来帮助决定得到什么以及如何最终对它们进行排序):
function getFiles(settings){
$.ajax("/directories", settings, function(directories) {
data.forEach(function (directory) {
$ajax("/directory/" + directory, settings, function(subdirectory) {
// and so on, in the innermost processing the file contents,
// but unable to return them.
});
});
});
}