js使用动态名称获取php变量

时间:2016-06-11 17:40:35

标签: javascript php html

我有一个调用js函数的简单按钮。在那里我想使用带有动态名称的php var。有什么想法吗?

<img>

当id参数为null时,if条件正常工作。但是向php var name添加id是问题......

<?php 
    $counter = 1;
    ${"fotos" . $counter++} = array(); 
    foreach ($row as $item) {
      ${"fotos" . $counter}[] = $item->img;
    }
 ?>; 
//will generate two vars:
       $fotos  = [img1];
       $fotos1 = [img1,img2];

<button type="button" onClick="verAdjuntos(<?php echo $counter; ?>)" class="btn btn-xs    btn-default"> View</button>
//parameter passed verAdjuntos(1) forxample

做好警报工作:

<script type="text/javascript">
  function verAdjuntos(id){
    if (id == null){
      var fotos  = <?php echo $fotos ?>; //output ok
      alert(JSON.stringify(fotos));
    }else{
      var fotos  = <?php echo  $fotos?> + id; /// how do name $fotos1 here?
      alert(JSON.stringify(fotos));
   };
  }
</script>

1 个答案:

答案 0 :(得分:0)

解决了从php变量中使用数组的问题。

<?php 
    $counter = 1;
    $fotos = array(); 
    foreach ($row as $item) {
      $allfotos[$counter] = array($item->img);
      $counter++;
    }
 ?>; 
//will generate two vars:
       $fotos[1]  = [img1];
       $fotos[2]  = [img1,img2];

<button type="button" onClick="verAdjuntos(<?php echo $counter; ?>)" class="btn btn-xs    btn-default"> View</button>



<script type="text/javascript">
function verAdjuntos(id){
    if (id == null){
        var fotos  = <?php echo $allfotos ?>;
        alert(JSON.stringify(fotos));
    }else{   
        <?php
            $js_array = json_encode($allfotos);
            echo "var javascript_array = ". $js_array . ";\n";
        ?>
        var fotos  = JSON.parse(javascript_array[id]); 
        alert(JSON.stringify(fotos));
    };


}
</script>