开发者

Is using a PHP defined variable in javascript possible? [duplicate]

This question already has answers here: How do I pass variables and data from PHP to JavaScript? (19 answers) Closed 1 year ago.

Is it possible to use in javascript a variable that was defined in earlier PHP code?

For example (in a page template PHP file):

<?php
$arr = array(-34开发者_开发知识库, 150);
?>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
...
var latlng = new google.maps.LatLng($arr);
...
}
</script>


Even better, use wp_localize_script() to pass your variables from PHP to javascript:

wp_enqueue_script( 'my-script', '/path/to/my-script.js' );

$loc_variables = array(
    'lat' => $latitude,
    'lon' => $longitude
    );

wp_localize_script( 'my-script', 'location', $loc_variables );

And then in your my-script.js, you can access those variables as location.lat and location.lon.


No, but you can make it a js var...

<script type="text/javascript">
var myArray = new Array(<?php echo $myArrayVals; ?>);
</script>


To extend Milo's answer, you can print out the variable in JS form using PHP's json_encode function.

For instance, if you have an array in PHP

<?php
 $cow=array('bat'=>false,'fob'=>'widget');

That you want in JS, then you could

<script>
  var cow=<?php echo json_encode($cow);?>; 
  // prints {"bat":false,"fob":"widget"}
  console.log(cow.fob);//'widget' of course

json_encode also takes care of quoting strings. Not all PHP values are json_encodable, of course - objects with methods can't be expressed as javascript values, but it doesn't sound like you're concerned about that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜