2015-10-06 98 views
-1

我想將js函數的變量發佈到我的數據庫中,我嘗試了幾件事,但它不會將它傳遞給php。我該如何解決這個問題?我已經添加了我正在使用的代碼。將javascript變量發佈到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> 
+2

https://en.wikipedia.org/wiki/Client-server_model:PHP發生在服務器中的任何呈現在客戶機上之前,包括JS。 – CD001

回答

0

json_encode返回包含JSON的字符串。因此你需要添加單引號。更改此:

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

要這樣:

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