I'd like to get a list of filenames that will later be stored into an array. The following code just displays directory listing in the same way Apache listing is displayed in a browser, e. g. 1234.txt 31-Aug-2016 13:17 35K
How to change it, so I get just the filenames?
<script type="text/javascript">
$(document).ready(function () {
$.get("dat/", function(data) {
$("#files").append(data);
});
});
</script>
<body>
<div id='files'></div>
</body>
Please try with below code. openFile function is useful to check whether it is file or folder. Please add more extensions in function as per your use.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var fileNames = new Array();
$.ajax({
url: "/test/",
success: function(data){
$(data).find("td > a").each(function(){
if(openFile($(this).attr("href"))){
fileNames.push($(this).attr("href"));
}
});
}
});
console.log(fileNames);
function openFile(file) {
var extension = file.substr( (file.lastIndexOf('.') +1) );
switch(extension) {
case 'jpg':
case 'png':
case 'gif': // the alert ended with pdf instead of gif.
case 'zip':
case 'rar':
case 'pdf':
case 'php':
case 'doc':
case 'docx':
case 'xls':
case 'xlsx':
return true;
default:
return false;
}
};
</script>
I ran into a similar problem. I needed to load all the file names from a specified directory. so I made a function
function loadFileNames(dir) {
return new Promise((resolve, reject) => {
try {
var fileNames = new Array();
$.ajax({
url: dir,
success: function (data) {
for(var i = 1; i < $(data).find('li span.name').length; i++){
var elem = $(data).find('li span.name')[i];
fileNames.push(elem.innerHTML);
}
return resolve(fileNames);
}
});
} catch (ex) {
return reject(new Error(ex));
}
});
}
then you call this function like this
loadFileNames('/resource/seed/files')
.then((data) => {
console.log(data);
})
.catch((error) => {
alert('Files could not be loaded. please check console for details');
console.error(error);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With