好的,所以创建了两个javascipt函数,我想在php循环中调用它们,同时将php变量作为参数传递给第二个函数
addElements($filePath)
这个filePath变量必须是内部循环中的最后一个变量,我想这样写不会从第一个循环中获得第一个变量
这是我想要的以及到目前为止已写的内容:
<script>
<?php foreach( glob( 'posts/*' ) as $filePath ){
//createPost(); call js function declared in header
foreach( glob( $filePath.'/*' ) as $filePath ){
//addElements($filePath) call second hs function declared in header here i pass the last $filePath from the second loop as parameter
}
}?>
</script>
再次尝试,但仍然行不通
<script>
<?php foreach( glob( 'posts/*' ) as $filePath ){
//createPost(); call js function declared in header
echo 'createPost()';
foreach( glob( $filePath.'/*' ) as $filePath ){
//addElements($filePath) call second hs function declared in header here i pass the last $filePath from the second loop as parameter
echo 'addElements('.$filePath.')';
}
}?>
PHP仅在服务器端执行,因此您不能拥有执行javascript函数的PHP循环(javascript =客户端)。但是,您可以在服务器上生成javascript代码,它将在客户端执行。
因此,简单的解决方案是编写如下代码:
<script>
<?php
foreach( glob( 'posts/*' ) as $filePath ){
echo 'createPost();'; // call js function declared in header
foreach( glob( $filePath.'/*' ) as $filePath ){
echo 'addElements("'.$filePath.'");'; // call second hs function declared in header here i pass the last $filePath from the second loop as parameter
}
}
?>
</script>
它将生成如下内容:
createPost();
addElements('filepathA');
addElements('filepathB');
addElements('filepathC');
createPost();
addElements('filepathD');
addElements('filepathE');
// ...
如您所见,这里没有循环。另一个解决方案是在服务器端创建数据数组,并使用json_encode
php函数获取可在客户端使用的javascript数据:
<?php
$results = [];
foreach( glob( 'posts/*' ) as $filePath ){
$subDirs = [];
foreach( glob( $filePath.'/*' ) as $filePath ){
$subDirs[] = $filePath;
}
$results[] = [
'dir' => $filePath,
'subDirs' => $subDirs
];
}
echo 'var data = ' . json_encode($results) . ';';
?>
现在,您有了一个可以照常使用的javascript数组:
for (var i = 0; i < data.length; i++){
createPost();
for (var j = 0; j < data[i].subDirs.length; j++){
addElements(data[i].subDirs[j]);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句