将PHP变量从.php传递到.js

I'm trying to pass the Lat and Long of a city into a gmaps function, in a separate file to where the php variable is created.

gmaps.js :

function getMap(lat) {
    alert(lat);
}

main.php :

<div id="map" onload="getMap(<?php echo json_encode($GLOBALS['city']->lat); ?>)"></div>

When I view the page source, I see this :

<div id="map" onload="getMap("51.713")"></div>

But the alert is displaying undefined.

The .js file is linked to the .php and other functions without passed variables work.

I need to be able to pass the variable as displayed in the source.

Try to use single quote in html:

<div id="map" onload='getMap(<?php echo json_encode($GLOBALS['city']->lat); ?>)'></div>

First of all, your quotes are messed up. The simplest way to fix that, would be to do this :

<div id="map" onload="getMap('<?php echo $GLOBALS['city']->lat); ?>')"></div>

That won't solve your problem, though. Another issue, is that you're using an onload on a div, which doesn't really work.

If all you want if your function to run after the div with id map has loaded, you could do this instead :

<div id="map"></div>
<script type="text/javascript">
   function getMap(lat) {
       alert(lat);
   }

   getMap('<?php echo $GLOBALS['city']->lat); ?>');
</script>

Alternatively, you could wait for your code to run when your entire page has loaded :

<div id="map"></div>
<script type="text/javascript">
   function getMap(lat) {
       alert(lat);
   }

   document.addEventListener("DOMContentLoaded", function(event) { 
       getMap('<?php echo $GLOBALS['city']->lat); ?>');
   });
</script>

Anyway, what I THINK you're trying to do, is something like this :

<div id="map"></div>
<script type="text/javascript">
   document.addEventListener("DOMContentLoaded", function(event) {
       var map = new GMaps({
           div : '#map',
           zoom : 16,
           lat : <?php echo $GLOBALS['city']->lat); ?>,
           lng : <?php echo $GLOBALS['city']->lng); ?>
       });
   });
</script>