views:

80

answers:

2

Is is possible to use jquery to take something like an images directory, collecting the filenames, and then printing a list of links on a page?

For example.. An images directory like so:

  • images/one.jpg
  • images/two.jpg
  • images/three.jpg

Then printing a index.html file like so:

  • img src="images/one.jpg"
  • img src="images/two.jpg"
  • img src="images/three.jpg"

Thanks

A: 

You would need to combine it with a serverside language to return the directory list. You can use JS to read from the filesystem directly. For example with php...

File: ls.php

<?php
  $dir = isset($_POST['dir']) ? $_SERVER['DOCUMENT_ROOT'].'/'.$_POST['dir'] : null;
  if(null !== $dir)
  {
     if($files = readdir($dir))
     {
        echo json_encode($files);
     }
  }
?>

in you js:

$.post(
  'ls.php', 
  {dir: 'images'}, 
  'JSON', 
  function(data){ 
    /* callback here the Data will be 
       an array of the files in dir */
  });

NOTE: dont use this code whole sale... you need to ad some security measures to the PHP portion, and i was to lazy to look up the argument order for $.post so you may need to modify that - but it should be enough to get the general idea :-)

prodigitalson
+1  A: 

Sounds like you're wanting to access the list of images that your downloading as part of the website.

You would be better to build the list serverside and encode that list within the page somehow (e.g. JSON), or even just iterate through the images, generating the HTML off the back of this.

Doing this with client-side script can be difficult, as there inherent security implications with regard to accessing the file system of the client. Consider the scenario where, in $(document).ready(), you read something from the file system and then perform an AJAX post with this information back up to the server!

James Wiseman
Pretty much I wanted to make it to where someone could dump files into a images directory, then have the images displayed on a page. Most likely into a ul.
Bruno
+1 here for noting the security implications.
prodigitalson
@Bruno. Not sure exactly what you are trying to achieve. Are you saying that you want the images dumped into a directory locally, and then for someone to visit some website to download some JavaScript that picks up the images in the directory and displays them?
James Wiseman