简体   繁体   中英

Javascript slideshow from PHP array

My goal is to pull the images from a file into a PHP array, then convert that array to a Javascript array that I could then use for my slideshow. That way I don't have to manually update my code when I add a new image to a file.

I am struggling with the Javascript part. I know that I can somehow use JSON function to convert the PHP array to Javascript array but I don't know how to use that function properly.

This is my PHP code that displays all pictures from a file called "slike":

 <?php
    $dir =          'slike';
    $file_display = array('jpg','jpeg','png');

    if (file_exists($dir) === false){
        echo "Directory ".$dir." doesn't exist!";
    }

    else {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file){
            $file_typeExplode = explode('.', $file);
            $file_type = strtolower(end($file_typeExplode));

            if($file !== '.' && $file !== '..' && in_array($file_type, $file_display) === true){
                echo '<img src = "', $dir, '/', $file, '" alt ="', $file, '" />';

            }
        }
    }
?>  

Not sure what that "converting to javascript array" part really means but I think you want to construct an array in javascript starting from what you have in the html page (DOM).

First of allyou have to identify the element of your page containing all the images, say it is an id of name foo :

<div id="foo">
    <img src....>
</div>

then in javascript you iterate on all the child elements of your div (that are your images) and construct an array with them.

var arry = [];
var images = document.getElementById('foo').childNodes;
for(i=0; i<nodes.length; i++) {
    arry.push(nodes[i]);
}

You could also give a class to all your images and iterate on all document.getElementsByClassName

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM