JS和PHP的新手,并修改幻灯片脚本以动态显示三个不同目录的内容。几乎可以让事情变得简单。
我遇到的一个问题是我修改的脚本使用以下静态代码来填充javascript数组:
variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']
variableslide[2]=['team_a/futuristic.jpg']
variableslide[3]=['team_a/lambo.jpg']
到目前为止,我的PHP代码正在动态枚举目录,然后将结果传递给Javascript:
<?php
// Header("content-type: application/x-javascript");
$team_a = array();
$team_b = array();
$team_c = array();
foreach (new DirectoryIterator('team_a') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_a[] = "team_a".'/'.$fileInfo->getFilename();
}
foreach (new DirectoryIterator('team_b/') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_b[] = $fileInfo->getFilename();
}
foreach (new DirectoryIterator('team_c') as $fileInfo) {
if($fileInfo->isDot() || !$fileInfo->isFile()) continue;
$team_c[] = $fileInfo->getFilename();
}
?>
<script type="text/javascript">
var variableslide = <?php echo json_encode($team_a, JSON_UNESCAPED_SLASHES)
?>
当我在运行完整代码时在Chrome中“检查元素”时,我可以看到文件名被传递给Javascript,但是,错过了0,1,2,3,4等我最终只会文件路径。结果如下:
var variableslide = ["team_a/blank.jpg","team_a/ford.jpg","team_a/futuristic.jpg","team_a/lambo.jpg"];
我一直在谷歌上搜索如何让var variableslide数组读取:
variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']
从PHP中提取数组索引号和文件名,并在JS中填充variableslide数组,使其读取与上面相同。当我从PHP脚本中print_r时,它会正确显示索引号和文本。任何人都可以帮我解决这个问题!谢谢!
答案 0 :(得分:0)
如果你看起来不像这样
variableslide[0]=['team_a/blank.jpg']
variableslide[1]=['team_a/ford.jpg']
在php文件中使用
<script type="text/javascript">
<?php
foreach($team_a as $i=>$v){ echo 'variableslide['.$i.']="'.$v.'";'."\n";}
?>
的插入内容
<script type="text/javascript">
var variableslide = <?php echo json_encode($team_a, JSON_UNESCAPED_SLASHES)
?>
* ***请注意,这是完全相同的事情!*