如何将php目录文件传递到javascript数组中?
我正在尝试从本地服务器上的目录创建图像幻灯片。我使用php通过如何将php目录文件传递到javascript数组中?,php,javascript,arrays,directory,Php,Javascript,Arrays,Directory,我正在尝试从本地服务器上的目录创建图像幻灯片。我使用php通过readDir()访问文件。我希望他们将变量传递到javascript数组中,然后访问我想要的任何特性。现在我只是想把它们打印到屏幕上,以确保它能正常工作,但我在屏幕上什么也看不到 <html> <head> </head> <body> <script type = "text/javascript"> var images = new Ar
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>
var images=新数组();
你可以用。例如:
<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>
对于(var i=0;i
在回音的开头有一个杂散的<,这将导致JS解析错误。当您执行此操作时,您是否从PHP或JS控制台中得到任何错误?您似乎有一个额外的我很抱歉,这不是我实际的代码,我在这里键入时打印错误。很抱歉
<?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>"; ?>