Skip to content
Advertisement

How can I iterate through all elements of local (server-side) folder?

Basically, I have a very simple website where the root directory looks like:

JavaScript

I want some way to recursively iterate through every file in the /images/ directory and display them in order in a section of my website. So for example, if /images/ contained:

JavaScript

then somewhere in index.html would contain:

JavaScript

My first idea was to do this using the document.write() function in stuff.js, but I couldn’t find a good way to iterate through the local file directory in Javascript. I saw something about AJAX, but all of those examples involved editing an existing file, which I obviously don’t want to do.

My current solution is just to manual create an array of strings containing all of the files in /images/, but doing this makes me think “There’s got to be a better way!”

Let me know if I’ve been unclear.

Thanks!

Advertisement

Answer

Perhaps the best way to do this is to use a server-sided language to do it for you, and to use an asynchronous Javascript request to display the data.

This sample uses PHP to list all the files in a specified directory, and an xmlhttprequest to load this output and convert the results into image tags:


getimages.php:

JavaScript

index.html (same directory as getimages.php):

JavaScript

Note that this is only an example. You’ll probably want to make sure that the AJAX call is successful, and that the JSON conversion works both in the server code and on the client.

Advertisement