简体   繁体   中英

get filenames in a given directory using jQuery

(I found some similar questions but none of them solved my problem so this is not a duplicated question I think)

I want to retrieve filenames in one of my folder using jQuery. I tried the following method but I still can't get each filename.

$.get(".", function(data) {
    $("#divID").append(data);
});

But I noticed that the type of 'data' is string and it contains filenames at the end of it like this:

<script>addRow("filename.csv","filename.csv",0,238618,"233 kB",1512119177,"12/1/17, 5:06:17 PM");</script>

So is there anyway I can retrieve the filenames from 'data'? (not by using regex)

You cannot read files in a client's machine. You may access them for development purpose by modifying a flag. Look at my answer here regarding this. After this proceed with the below code.

Both works.

Using PURE JAVASCRIPT :

 var filenames=[], foldernames=[]; var url = "file:///Users/Default/Downloads"; var req = new XMLHttpRequest(); req.open("GET",url,true); req.onreadystatechange=function(){ if(req.readyState === 4) { document.write(req.responseText); getNames(); } }; req.send(); function getNames() { var files = document.querySelectorAll("a.icon.file"); var folders = document.querySelectorAll("a.icon.dir"); files.forEach(function(item){filenames.push(item.textContent)}) folders.forEach(function(item){foldernames.push(item.textContent.slice(0,-1))}) console.log(filenames); console.log(foldernames); }

Using JQUERY :

 var filenames=[], foldernames=[]; $.get("file:///Users/Default/Downloads",function(response){ document.write(response); getNames(); }); function getNames() { var files = document.querySelectorAll("a.icon.file"); var folders = document.querySelectorAll("a.icon.dir"); files.forEach(function(item){filenames.push(item.textContent)}) folders.forEach(function(item){foldernames.push(item.textContent.slice(0,-1))}) console.log(filenames); console.log(foldernames); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM