简体   繁体   中英

How to scroll through an array of pictures with PHP and Javascript

I have a sql query that pulls an array that contains file paths to my images.

It is store in the variable $rows and I can access individual paths by indexing throught...

IE.

$rows[0]...$rows[n]

How can I utilize java script to step through this.

Final goal is for the picture to appear with a "Next" "Previous" button under it. Hitting next would show the next image (without a refresh)

echo $rows[0]; 

would print

images/a.png

Maybe using PHP's json functions you can convert your PHP array to a js array... and then use javascript functions to control which picture to show

<script type="text/javascript">
    var images = <?php echo json_encode($rows) ?>, counter = 0;

    function prevImage() {
        counter = (counter<=0)?images.length-1:counter-1;
        var i = document.getElementById('myImage');
        i.src = images[counter];
    }
    function nextImage() {
        counter = (counter==images.length-1)?0:counter+1;
        var i = document.getElementById('myImage');
        i.src = images[counter];
    }
</script>

and

<img src="img/0.jpg" id="myImage" />
<a href="#" onClick="prevImage(); return false;">Previous</a> - <a href="#" onClick="nextImage(); return false;">Next</a>​

Here is a little example to move your php array to a javascript array:

<?php
    $row = array("image/image1","image/image2","image/image3");
?>
<html>
    <head>
    <title>Sample Array</title>
    <script>
    var jsArray = new Array();
    <?php 
    for ($i=0; $i<3; $i++)
    {
         echo "jsArray[$i] = '$row[$i]';";  
    }
    ?>
    for(i = 0; i < jsArray.length;i++)
    {
        alert(jsArray[i]);
    }
    </script>
    </head>
    <body>
        <span>Sample Array</span>
    </body>
</html>

Good luck!

Get your PHP array (server-side) to Javascript (clientside)

There are quite a few ways to go about doing this, but I'd recommend JSON . It has numerous advantages, but the most obvious one is you can store arrays and javascript objects as a string. If you're not familiar with it, this would be an excellent time to start including it in your workflow, considering you have to deal with Javascript.

PHP

  1. Turn Array to JSON:

    $jsonResults = json_encode($arrayOfResults);

  2. Get JSON from PHP to Javascript:

     <script> var myAppsData = {}; myAppsData.slideshowJSON = JSON.parse($jsonResults); </script> 

Now your JSON object is accessible to Javascript at myAppsData.slideshowJSON .

The rest of the work is as simple as iterating through the object with a for loop (just like you would in PHP), grabbing the content and doing what you want with it.

Cheers!

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