Using PHP Variables in Javascript with JSON -
this question has answer here:
<?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
Post a Comment