如何传递php目录文件到javascript数组


How to pass php directory files into javascript array?

我正在尝试从本地服务器上的目录创建图像幻灯片。我使用php访问使用readDir()的文件。如果他们想将变量传递到javascript数组中,然后访问我想要的任何功能。现在我只是试着把它们打印到屏幕上,以确保它能工作,但是我在屏幕上根本没有得到任何东西。

<html>
  <head>
  </head>
  <body>
    <script type = "text/javascript">
      var images = new Array();
<?php
$dp = opendir("img/slideshow");
while($currentFile !== false){
  if($currentFile != "." && $currentFile != ".."){
    $currentFile = readDir($dp);
    echo("images.push('{$currentFile}');");
  }
}
?>
      for(var i = 0; i < images.length; i++){
        document.write("<a href = '" + images[i] + "'>" + images[i] + "</a>");
      }
    </script>
  </body>
</html>

这对我来说似乎很合乎逻辑。我从创建javascript数组开始,然后在php部分打开并读取目录,然后回显一行代码,将当前文件推入javascript数组。然后它应该打印出每个数组项,但是我得到一个空白屏幕。*注意:如果我将文件放入php数组并打印出来,它工作得很好,但我不能通过javascript访问数组并为其添加动画*

您可以使用json_encode()。例如:

<html>
  <head>
  </head>
  <body>
    <script type = "text/javascript">
<?php
$dp = opendir("img/slideshow");
$arrayjs = array();
while($currentFile !== false){
  if($currentFile != "." && $currentFile != ".."){
    $currentFile = readDir($dp);
    $arrayjs[] = $currentFile;
  }
}
echo "var images = " . json_encode($arrayjs) . ";";
?>
      for(var i = 0; i < images.length; i++){
        document.write("<a href = '" + images[i] + "'>" + images[i] + "</a>");
      }
    </script>
  </body>
</html>
<?php
$dir="img/slideshow";//set the working directory
$pics= scandir($dir) ;//Makes a array with all the items of the array
unset($pics[0],$pics[1]);//first and second ellement are the "."".." is nesecery to unset!
$string = '<script type ="text/javascript">var images =[ ';
foreach($pics as $key => $item) {
$string.='"'.$item.'",';
}
echo substr($string, 0, -1)."];</script>"; ?>