user120944
user120944

Reputation:

Print Filenames from Directory w/ jQuery

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:

Then printing a index.html file like so:

Thanks

Upvotes: 0

Views: 1623

Answers (2)

prodigitalson
prodigitalson

Reputation: 60413

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 :-)

Upvotes: 1

Mutation Person
Mutation Person

Reputation: 30520

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!

Upvotes: 1

Related Questions