Basically, I have a very simple website where the root directory looks like:
/images/
index.html
stuff.js
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:
images/a/a.png
images/b.png
images/c.jpg
....
then somewhere in index.html would contain:
<img src="images/a/a.png" />
<img src="images/b.png" />
<img src="images/c.jpg" />
....
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!
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
xmlhttprequestto load this output and convert the results into image tags:getimages.php:
index.html (same directory as getimages.php):
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.