Assigining non-string PHP variables in JS
I have latitude/lognitude variables that are not strings 开发者_JAVA百科and I need to put them into JavaScript variables. I currently try to do something like this which does not work:
lat = <?= $objkey->lat ?>;
lng = <?= $objkey->lng ?>;
But wrapping it in strings, breaks the maps functions when I use the lat/lng variables.
What is the right way to go about this?
Here is the URL where this is happening: http://www.comehike.com/outdoors/parks/trailhead.php
I would generally use json_encode for this: if it's Serializable:
json_encode($yourobject);
Otherwise:
var coordinates = <?php echo json_encode($array('lat' => $object->lat, 'lng'=> $object->lng); ?>
console.log(coordinates);
console.log(coordinates.lat);
Edit: this answer is probably still sound advise, but here there seems to be an error with echoing the object. Is the object valid?
It's not outputting anything from PHP.
In your code:
lat = ;
Resulting in a Uncaught SyntaxError: Unexpected token ;
You are not outputting anything:
Make sure that you actually have output, which could be the issue.
The issue could be caused by several things, first thing I'd check is to make sure PHP short tags is really enabled, or simply don't use them, the next thing would be to make sure the variables actually have values. Try the following:
lat = <?php echo isset($objkey->lat) ? $objkey->lat : 0; ?>;
lng = <?php echo isset($objkey->lng) ? $objkey->lng : 0; ?>;
精彩评论