Post javascript variables to php

Post javascript variables to php

本文关键字:php to variables javascript Post      更新时间:2023-09-26

我试图从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>

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

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

:

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