我可以使用Javascript来获取文件目录列表吗?
我使用的是客户端Javascript,并且希望获取一个文件夹中所有文件的列表,我相信这个文件夹与我的.html文件位于同一台服务器上。我对这个术语非常陌生,所以如果我不准确或只是出错,我会提前道歉。
I'm using client-side Javascript and want to get a list of all the files in a folder that I believe is hosted on the same server as my .html file. I'm very unfamiliar with the terminology so I apologize in advance if I'm inaccurate or just plain wrong.
我目前使用 d3.text (js / data / nodes#.csv,text / csv,someFunction)
来加载要使用的数据文件。我想,由于所有的文件名我想要的模板化的方式相同,我可以通过循环遍历所有可能的数字,并只获取有效调用的文件名,通过解决方案:
I currently use d3.text("js/data/nodes#.csv", "text/csv", someFunction)
to load in a data file to work with. I figure that since all the filenames I want are templated the same way, I can hack a solution by looping through all possible numbers and only get the filenames of valid calls, like so:
function getDirList() {
var possiblePathsList = something predetermined;
var directoryList = [];
possiblePathsList.forEach(function(path){
if (isPath(path)) { directoryList.push(path); }
});
return directoryList;
}
function isPath(path){
d3.text(path, "text/csv", function(data){
return (data !== null);
});
}
因为我可以用这种非常垃圾的方式得到一个列表,做一些(多,更多)优雅的方法来实现我的目标。这是可能的吗?
Because I can get a list in this very rubbish way, I presume there must be some (much, much more) elegant method of achieving my goal. Is this possible?
根据定义,如果你使用客户端javascript,它没有访问服务器的文件夹结构体。你可以写一个单独的ajax调用,或者将有一个服务器端脚本(在任何langauge),将通过目录并打印出来到一个json文件,然后你可以使用你的javascript处理。像这样:
By definition if you're using client side javascript, it doesn't have access to the server's folder structure. You could write a separate ajax call or something that would have a server side script (in whatever langauge) that would go through the directories and print them out to a json file that you would then be able to process with your javascript there. Something like this:
ajax.php:
ajax.php:
$directory = "temp/";
$dir = opendir($directory);
$structure = array();
while($file = readdir($dir)){
$structure[] = $file;
}
print json_encode($structure);
exit();
然后你将有一些javascript调用该脚本并通过json文件解析
Then you will have some javascript that calls that script and parses through the json file