开发者

How do I use PHP to supply info to JavaScript?

开发者 https://www.devze.com 2023-01-13 07:33 出处:网络
I have a simple image-looping script that changes the src of an image. function cycleNext() { ++imgIndex;

I have a simple image-looping script that changes the src of an image.

function cycleNext()
{
    ++imgIndex;

    if(imgIndex>imgCount)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

However, at present, I'm (shudder) manually entering imgCount in my script. The alternative is server-side, but I don't k开发者_JAVA技巧now how to fetch this information. I imagine it's pretty simple, though.

How can I use PHP to supply this script with the number of images in the folder?


<?php
$directory = "Your directory";
$filecount = count(glob("" . $directory . "*.jpg"));
$filecount += count(glob("" . $directory . "*.png"));
?>

Repeat the 2nd line for each extension you wish to count.

function cycleNext()
{
    ++imgIndex;

    if (imgIndex > <?php echo $filecount;?>)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

That should do it.

EDIT:

function cycleNext(imgCount)
{
    ++imgIndex;

    if (imgIndex > imgCount)
    {
        imgIndex = 1;
    }

    setImgSrc(imgIndex);
}

Then when you call cycleNext, call it with the variable.

cycleNext(<?php echo $filecount; ?>);


if the .js file is a separate file. then you can do this:

change the .js for a .php

then you can add <?php ?> tags just like you do in your .php files.

just don't forget to add the header in the code, indicating that the file is a javascript file. like that:

<?php header("Content-type: text/javascript"); ?>

and you will call the file with it's actual name src="file.php"


You can do it in three ways:

  1. Making your .js file a .php file (with the correct mime-type) and just use an echo in that .js.php-file
  2. include the javascript to the <head> tag of your page
  3. echo a variable into a <script> tag in your <head> and use it in your javascript file. Example:

    <script type="text/javascript">
      var imgCount = <?php echo $imagecount ?>
    </script>;
    


During the generation of the HTML code, simply insert a <script> line, for instance

  echo '<script type="text/javascript">';
  echo 'var imgCount=' . $NumberOfImages . ';';
  echo '</script>';

Just ensure that line is provided before cycleNext() is called (or imgCount is used).

0

精彩评论

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

关注公众号