将javascript变量发布到php

时间:2015-10-06 12:50:48

标签: javascript php

我正在尝试将变量从js函数发布到我的数据库中,我尝试了几件事,但它不会将它传递给php。我怎么解决这个问题?我已经添加了我正在使用的代码。

任何帮助都将受到高度赞赏

<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<?php
// Opens a connection to a mySQL server
$connection=mysqli_connect ('localhost', 'root','', 'koopwoningen');
if (!$connection) {
  die("Not connected : " . mysqli_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT Adres FROM geocodetest");
$result = mysqli_query($connection, $query);
$data = array();
if (!$result) {
  die("Invalid query: " . mysqli_error());
}

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
       $data[] = $row["Adres"];

    }
} else {
    echo "0 results";
}
?>

<script type="text/javascript">

var adresses = <?php echo json_encode($data) ?>;
var geocoder = new google.maps.Geocoder();

for(i=0;i<adresses.length;i++){
var address = adresses[i];

geocoder.geocode( { 'address': address}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();

    if (window.XMLHttpRequest) {
                        xmlhttp = new XMLHttpRequest();
                    }

                    xmlhttp.open("POST", "geocode.php?latitude=" + latitude + "&longitude=" + longitude);
                    xmlhttp.send();

    alert(latitude + ", " + longitude);

    } 

}); 
}



</script>
<?php

$lati = isset($_POST['latitude']);
$lngi = isset($_POST['longitude']);

$query = mysqli_query($connection, "INSERT INTO geocodetest (lat, lng) VALUES ($lati, $lngi)") or die(mysql_error());  
?>
</html>

1 个答案:

答案 0 :(得分:0)

json_encode返回包含JSON的字符串。因此,您需要添加单引号。改变这个:

var adresses = <?php echo json_encode($data) ?>;

对此:

var adresses = '<?php echo json_encode($data) ?>';