简体   繁体   English

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

[英]How to pass array values from PHP to JavaScript?

Okay. 好的。 So i've been here all day, reading and following all the solutions about this topic but i got nothing. 所以我整天都在这里,阅读并关注有关该主题的所有解决方案,但我一无所获。 Nothing works. 什么都没有。 Can you show me how to do it, with complete and understandable example. 您能通过完整且易于理解的示例向我展示如何做到这一点。 Im new to JavaScript and PHP, so how can i get array values from a PHP file to JavaScript. 我是JavaScript和PHP的新手,所以如何从PHP文件到JavaScript获取数组值。 I tried doing this: var locations = <?php echo json_encode($location); ?>; 我尝试这样做: var locations = <?php echo json_encode($location); ?>; var locations = <?php echo json_encode($location); ?>; but i gives me error. 但我给我错误。 and no one answered why. 没有人回答为什么。 This code here: 这段代码在这里:

 <!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> 

i want to change the value of variable locations from the value from my database. 我想从数据库中的值更改变量locations的值。 so i got this PHP file: 所以我得到了这个PHP文件:

 <?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";} ?> 

it works fine. 它工作正常。 it outputs the data from the database. 它从数据库输出数据。 now what i want to know is how can i convert that value from the database to a value i can use in place of the locations variable so that the markers will appear on the map? 现在我想知道的是如何将数据库中的值转换为可以代替locations变量使用的值,以便标记将出现在地图上? var locations = <?php echo json_encode($location); ?>; this guy give me error, i followed every instruction i can, but still it's error. 这个家伙给我错误,我按照我的所有指示进行操作,但仍然是错误的。 can u modify my code so that it works or can u just point me out in the WORKING/FUNCTIONAL code there is to your knowledge. 您是否可以修改我的代码以使其起作用,还是可以在您所知的工作/功能代码中向我指出。 Please, help me. 请帮我。 I'm in deep trouble here. 我在这里很麻烦。

Try to change location[] variable from : 尝试从以下location[]更改location[]变量:

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

to

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

I have added full code below and its working : 我在下面添加了完整的代码及其工作方式:

<?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>

Your array is not "realy" an array if your code is : 如果您的代码是,则您的数组不是“真正”的数组:

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

I think the result will be somthing like this : 我认为结果将是这样的:

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

.....
</script>

try with : 尝试:

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

Edit: I don't recommend to use this mean to pass PHP array to JS beacause it overload the html page and navigator can't cahe the content of your array. 编辑:我不建议使用此方法将PHP数组传递给JS,因为它会使html页面超载并且导航器无法处理数组的内容。 the beter way to do this is to use Ajax function at the page loading with this http://api.jquery.com/jquery.ajax/ 更好的方法是在加载此http://api.jquery.com/jquery.ajax/的页面上使用Ajax函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM