问题
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.
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?
回答1:
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:
$directory = "temp/";
$dir = opendir($directory);
$structure = array();
while($file = readdir($dir)){
$structure[] = $file;
}
print json_encode($structure);
exit();
Then you will have some javascript that calls that script and parses through the json file
来源:https://stackoverflow.com/questions/26150336/can-i-use-javascript-to-get-a-file-directory-list