如何在JavaScript中从PHP访问数组数据

时间:2016-02-08 03:56:10

标签: javascript php arrays json

我在PHP中有这个代码。我工作得很好:



<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tsunami_simulation";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

//========================================================
	$sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
	$result = mysqli_query($conn, $sql);
		
	if(mysqli_num_rows($result) > 0){
		
		for($i=0;$i<$num_rows;$i++){
			$row=mysql_fetch_row($result);

			$location[]= $row[0].', '.$row[2].', '.$row[1].','.($i+1);
			//echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
		}
		
	}else{echo "0 results";}
?>
&#13;
&#13;
&#13;

现在,我想要做的是在javascript中从这个PHP文件访问数组结果。我尝试使用JSON.parse()。但我没有工作。 我使用了这段代码:var locations = '<?php echo json_encode($location); ?>';我没有给出错误。然后是locations = JSON.parse(locations),它返回<?php echo json_encode($location); ?>这个,而不是数据。我怎样才能获得正确的数据,只要它有效,任何方法都会做,请帮助我。顺便说一句,我想从wamp中的数据库中获取数组,并使用数组中的坐标将标记放在googlemap上。请帮帮我!..

编辑:我必须访问数据的其他代码:

&#13;
&#13;
<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>New 1 -- Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?v3" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

<?php include 'Location.php';?>
  
  <script type="text/javascript">
    var locations = <?php echo json_encode($location, JSON_HEX_TAG); ?>;

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(6.40, 125.60),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {

		loc_array = locations[i].split(",");

		marker = new google.maps.Marker({
			position: new google.maps.LatLng(loc_array[1], loc_array[2]),
			map: map
		});

		google.maps.event.addListener(marker, 'click', (function(marker, i) {
			return function() {
				infowindow.setContent(loc_array[0]);
				infowindow.open(map, marker);
			}
		})(marker, i));
    }
  </script>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

$location[]= array($row[0], $row[2], $row[1], $i+1);

然后

var locations = <?php echo json_encode($location, JSON_HEX_TAG); ?>

注意:不需要JSON.parse,没有引号,特别是不能手动连接变量以形成准数组。

编辑:强烈推荐JSON_HEX_TAG,如果你有PHP 5.3.3+,因为普通json_encode不太安全。