如何将php变量分配给javascript变量

时间:2013-12-11 11:52:52

标签: javascript php

<?php
$query = mysql_query("SELECT  products_zipcode FROM products ")or die(mysql_error());

while($row = mysql_fetch_array($query))
{
  $zip = $row['products_zipcode'];
}
?>

这里如何将$ zip变量值赋给java脚本变量var address = zip;

<script type="text/javascript">
function codeAddress(zip) {

  var address = zip;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
</script >

这里更改了代码 如 根据答案

<?php
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("coachup_db1") or die(mysql_error());
?>

<?php
$query = mysql_query("SELECT  products_zipcode FROM products ")or die(mysql_error());

while($row = mysql_fetch_array($query))
{
  $zip[] = $row['products_zipcode'];

// echo("codeAddress($zip)");
}
?>
    <div id="map-canvas"></div>
  <style>
    #map-canvas {
        width: 300px;
        height: 200px;
        margin: 0px;
        padding: 0px;
         border: 0px; padding: 0px;
      }

    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script type="text/javascript">

var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 4,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {

  var address = <?php echo json_encode($zip); ?>;
  var overallcontent = <?php echo json_encode($zip); ?>;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'load', codeAddress);

    </script>

3 个答案:

答案 0 :(得分:2)

您可以使用以下方法将php变量分配给javascript变量。

var address =<?php echo json_encode($zip) ?>;
另一方面,

如果要将php数组分配给javascript变量而不是:

var overallcontent = <?php echo json_encode($type); ?>;

其中$type是一个php数组。

答案 1 :(得分:1)

var address = "<?php echo $zip ?>";

答案 2 :(得分:0)

只需echo它并将其存储在JavaScript变量中。方法如下:

var address = "<?php echo $zipCode' ?>";