Using PHP Variables in Javascript with JSON -


<?php    $heros=array("spiderman","batman","superman"); ?>  <script type="text/javascript">    var heros = <?php echo $heros;?> // don't want this.    for(i=0; i<3; i++)    {         if(heros[i]=='spiderman')       {         alert('hey! spiderman.');       }    } </script> 

i want use php array inside javascript loop don't want reopen php tags inside <script></script> tags. how can use php variables in javascript?

var heros = <?php echo json_encode($heros);?> // have this. 

if don't want open php tags inside js, you'll have issue ajax request server , grab data asynchronously. code (using jquery shortness):

$.getjson('/url/that/responds/with/json', function(heros) {    for(i=0; i<3; i++)    {         if(heros[i]=='spiderman')       {         alert('hey! spiderman.');       }    }  }); 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -