How to load all the images from one of my folder into my web page, using Jquery/Javascript

后端 未结 14 2304
情深已故
情深已故 2020-11-22 10:18

I have a folder named \"images\" in the same directory as my .js file. I want to load all the images from \"images\" folder into my html page using Jquery/Javascript.

<
14条回答
  •  误落风尘
    2020-11-22 10:58

    Here is one way to do it. Involves doing a little PHP as well.

    The PHP part:

    $filenameArray = [];
    
    $handle = opendir(dirname(realpath(__FILE__)).'/images/');
            while($file = readdir($handle)){
                if($file !== '.' && $file !== '..'){
                    array_push($filenameArray, "images/$file");
                }
            }
    
    echo json_encode($filenameArray);
    

    The jQuery part:

    $.ajax({
                url: "getImages.php",
                dataType: "json",
                success: function (data) {
    
                    $.each(data, function(i,filename) {
                        $('#imageDiv').prepend('
    '); }); } });

    So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.

    Had some help on the php part from 1

提交回复
热议问题