如何将数组值从PHP传递给JavaScript?

时间:2016-02-08 08:39:39

标签: javascript php jquery html arrays

好。所以我整天都在这里,阅读并遵循关于这个主题的所有解决方案,但我一无所获。什么都行不通。你能用完整且可理解的例子告诉我如何做到这一点。我是JavaScript和PHP的新手,所以如何从PHP文件中获取数组值到JavaScript。我试过这样做:var locations = <?php echo json_encode($location); ?>;但是我给了我错误。并没有人回答为什么。这段代码在这里:

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

  <script type="text/javascript">
    var locations = [
  ['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
  ['Camarillo Household', 6.4345278, 125.58975, 2],
  ['Perez Household', 6.4343889, 125.59202777777777, 3],
  ['Usman Household', 6.4338056, 125.59191666666666, 4],
  ['Lim Household', 6.4333889, 125.59419444444444, 5]
];

    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++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

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

我想从数据库中的值更改变量locations的值。所以我得到了这个PHP文件:

&#13;
&#13;
<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";

// 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){
		// output data of each row
		
		for($i=0;$i<mysqli_num_rows ( $result );$i++){
			$row=mysqli_fetch_row($result);

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

它工作正常。它从数据库输出数据。现在我想知道的是我如何将数据库中的值转换为我可以用来代替locations变量的值,以便标记出现在地图上? var locations = <?php echo json_encode($location); ?>;这家伙给我错误,我按照我的每条指令,但仍然是错误。你可以修改我的代码,以便它可以工作,或者你可以在工作/功能代码中指出我知道你的知识。请帮我。我在这里遇到了很大的麻烦。

2 个答案:

答案 0 :(得分:2)

尝试更改location[]变量:

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

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

我在下面添加了完整代码及其工作原理:

<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";

// 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){
    // output data of each row

    for($i=0;$i<mysqli_num_rows ( $result );$i++){
        $row=mysqli_fetch_row($result);

        $location[]= array($row[0],$row[1],$row[2],($i+1));
        //echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
    }
}else{echo "0 results";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
    type="text/javascript"></script>
</head>
<body>
    <div id="map" style="width: 500px; height: 400px;"></div>

    <script type="text/javascript">
    /*var locations = [
  ['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
  ['Camarillo Household', 6.4345278, 125.58975, 2],
  ['Perez Household', 6.4343889, 125.59202777777777, 3],
  ['Usman Household', 6.4338056, 125.59191666666666, 4],
  ['Lim Household', 6.4333889, 125.59419444444444, 5]
];*/
var locations = <?php echo json_encode($location); ?>;


    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++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

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

答案 1 :(得分:0)

你的数组不是“真正的”数组 如果你的代码是:

#include <iostream>
#include <memory>
using namespace std;

class MyOtherClass
{
public:
    MyOtherClass()
    {
        throw std::runtime_error("not working");
    }
};

class MyClass
{
public:
    typedef std::unique_ptr<MyOtherClass> MyOtherClassPtr;

    MyClass()
    {
        try
        {
            other = std::make_unique<MyOtherClass>();
        }
        catch(...)
        {
            cout << "initialization failed." << endl;
        }

        cout << "other is initialized: " << (other ? "yes" : "no");
    }

private:
    std::unique_ptr<MyOtherClass> other;
};

int main()
{
    MyClass c;

    return 0;
}

我认为结果将是这样的:

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

尝试:

<script type="text/javascript">
    var locations = [["Municipal Hall, 6.414333734068895, 25.61093270778656, 1"],["Camarillo Household', 6.4345278, 125.58975, 2"],......];

.....
</script>

编辑: 我不建议使用这个意思来将PHP数组传递给JS,因为它会使html页面重载,导航器无法控制数组的内容。更好的方法是使用此http://api.jquery.com/jquery.ajax/

在页面加载时使用Ajax函数