How can I get a list of images in a folder using javascript?

☆樱花仙子☆ 提交于 2019-12-08 10:36:31

问题


I have a folder tree like so:

  1. ProjectFolder
    • img
      • fjdkslajsd.jpg
      • fjowefwask.jpg
      • fweoifqadf.jpg
      • ...
    • scripts
      • script.js
      • jquery.js
    • stylesheets
      • styles.css
    • index.html

The index.html file pretty much just links to the scripts and stylesheet, and contains a div to hold my content. What I want to do is have the script.js find all the names of the images in the img folder and put them in a list so that I can later cycle through the list and display the images one by one. The end result would essentially look like a powerpoint that continuously cycles through the images in the img folder and displays them.

I hope that clears up any of your questions, so here's mine... How would I capture a list of strings that contain the names of the images in the img folder? I already know how to cycle through the list and display the images, but I have no idea how I would tackle GETTING the list.


回答1:


Unless you have some kind of interface server-side which gives you a parseable structure representing the project folder / file structure, you won't be able to use or handle this information in javascript.

If you have PHP available on your server, you can generate a javascript array using plain output:

<script type="text/javascript">
    var imageList=[<?php
        $dir='/projectdir/img/';
        $files = scandir($dir);
        foreach((array)$files as $file){
           if($file=='.'||$file=='..') continue;
           $fileList[]=$file;
        }
        echo "'".implode("','", $fileList)."'";
    ?>];
</script>

After the browser parses this, imageList will contain an array of all the files in the given folder. You can then use this array for further processing / handling.




回答2:


You would have to make a ajax request to a server side script that will give you a list of files from either an arbitrary directory (this could be dangerous) or specifically the images directory (probably the better way to handle it). Once you have the list of files from the server side script, you can use javascript to create the image elements and add them to the DOM once it is ready to be modified.

If you're using PHP, you can use PHP to add each of those images to the page in the appropriate place as well and save yourself an ajax request.



来源:https://stackoverflow.com/questions/20317120/how-can-i-get-a-list-of-images-in-a-folder-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!