2016-06-11 11 views
-2

js関数を呼び出す単純なボタンがあります。そこに私は動的名を使用してPHPのvarを使用します。どんなアイデアをお願いしますか?js動的名でphp変数を取得する

<?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 

idパラメータがnullの場合、if条件は正常に機能します。しかし、PHPのVAR名にIDを追加することが問題である...

<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> 

はあまりにも警告細かい作業を行う:

alert(JSON.stringify(fotos1)); 
+0

通報しますか?何が問題ですか? – nicael

+0

あなたは混乱しています。 PHPはサーバー上で実行され、JSはクライアント上で実行されます。彼らは直接対話することはできません。しかし、問題それは問題が何であるかだ場合、私は実際に私は複数のPHPのVARSを生成し、サーバから、... –

+0

ハズレを伝えることができず、クライアントからのyがこれらのVARS –

答えて

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> 
関連する問題