开发者

Print Filenames from Directory w/ jQuery

Is is poss开发者_如何学Pythonible 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


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜