在 PHP 循环中调用 js 函数,同时将 php 变量作为参数传递给其中一个函数


Call js functions inside PHP loops while passing php variable as parameter to one of the functions

好的,所以创建了两个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');
// ...

如您所见,这里没有循环。另一种解决方案是在服务器端创建一个数据数组,并使用 php 函数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]);
    }
}