将变量从 html 传递到 javascript 再到 php

Passing variables from html to javascript to php

我正在尝试对用户提交的地址进行地理编码并将其存储到数据库中。该表单调用 php 文件,其中 javascript 检索地址并对其进行地理编码。然后将 lat 和 lng 值传递给 php 并存储在数据库中,但是数据库中的唯一值是零。

HTML 文件:

 <html>
  <body>
    <form action="registerEvent.php" id="form" method="post">       
        <input id="address" name="address" placeholder="Adrese" type="text">                    
        <button type="submit" id="submit">Send</button>             
    </form>
  </body>
</html>

registerEvent.php:

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var geocoder;
var inputLat;
var inputLng;

function codeAddress() {

    geocoder = new google.maps.Geocoder();

  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {

    var inputLat = event.latLng.lat(); 
    var inputLng = event.latLng.lng();    

    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

}

function passvariable() { 
  window.location.href = "registerEvent.php?lat=" + inputLat;
  window.location.href = "registerEvent.php?lng=" + inputLng; 
}

    codeAddress();
    passvariable();

</script>



<?php
    require("dbinfo.php");

    $connection=mysqli_connect ('localhost', $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

    $lat =$_GET['inputLat']; 
    $lng =$_GET['inputLng']; 

    $sql = "INSERT INTO sometable (lat, lng)
VALUES ('$lat', '$lng')";

    if (!mysqli_query($connection,$sql)) {
      die('Error: ' . mysqli_error($connection));
    };

    mysqli_close($connection);
?>

您调用了 window.location.href 两次,PHP 部分的变量似乎不正确($_GET['inputLat'] 而不是 lat$_GET['inputLong'] 而不是 lon)

如果HTML文件是一个单独的文件,那么你需要用不同的方式获取地址: 替换

var address = document.getElementById('address').value;

var address = "<?php echo $_POST['address']; ?>"

JS 函数应该看起来更像这样

<script src="https://maps.googleapis.com/maps/api/jsv=3.exp&signed_in=true">
</script>
<script> 
var geocoder;
var inputLat;
var inputLng; 

function codeAddress() {
  geocoder = new google.maps.Geocoder();
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    var inputLat = event.latLng.lat(); 
    var inputLng = event.latLng.lng();    
    window.location.href = "registerEvent.php?lat=" + inputLat + "&lng=" + inputLng;
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

}
codeAddress();
</script>

和 PHP 部分:

    // ...
    $lat =$_GET['lat']; 
    $lng =$_GET['lng']; 

    if (!empty($lat) && !empty($lng)) {    
       $sql = "INSERT INTO sometable (lat, lng) VALUES ('$lat', '$lng')";
       if (!mysqli_query($connection,$sql)) {
         die('Error: ' . mysqli_error($connection));
       };
    }

    mysqli_close($connection);

如果所有内容都在同一个文件中,则表单按钮应更改为如下所示:

<button type="button" id="submit" onclick="codeAddress()">Send</button>    

有一次,A 使用此代码段从一个地址获取 lat/lng,全部在 PHP(旧 API)中:

$address = "......";
$json = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=".urlencode($address));
$json = json_decode($json);

if ($json->status == "OK")
    return $json->results[0]->geometry->location;

javascript 正在寻找一个值

var address = document.getElementById('address').value;

在 html 输入中没有值:

<input id="address" name="address" placeholder="Adrese" type="text">

在您的代码中,表单对 PHP 页面执行 POST 但您 post 只有地址字段而没有从 google api.

加上您调用的 API 给出了一个复杂的 return 类型,您应该检查它...要获得纬度和经度,您必须从数组中选择一个元素并检查 return 中的内容=13=]...(您可以检查:https://developers.google.com/maps/documentation/javascript/reference#GeocoderResult

因此,首先,在 post 表单之前进行 ajax 调用以获取坐标。

只需添加 onsubmit="return codeAddress();" 然后在您的 codeAddress 函数中添加一个 return false; 以防止默认操作(防止提交表单本身)并通过 GET 等函数将数据发送到 registerEvent.php这个。

在你的HTML中:

<html>
  <head>
     <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
     <script type="text/javascript">
        function codeAddress() {
           var geocoder = new google.maps.Geocoder();
           var address = document.getElementById('address').value;
           geocoder.geocode( { 'address': address}, function(results, status) {
             if (status == google.maps.GeocoderStatus.OK) {
               var inputLat = results[0].geometry.location.lat(); 
               var inputLng = results[0].geometry.location.lng();    
               window.location.href = "registerEvent.php?inputLat=" + inputLat + "&inputLng=" + inputLng;
             } else {
               alert('Geocode was not successful for the following reason: ' + status);
             }
           });
           return false;
        }
     </script>
  </head>
  <body>
    <form action="registerEvent.php" id="form" method="post" onsubmit="return codeAddress()">       
       <input id="address" name="address" placeholder="Adrese" type="text">                    
       <button type="submit" id="submit">Send</button>             
    </form>
  </body>
</html>

在你的PHP中:

<?php
require("dbinfo.php");
$connection=mysqli_connect ('localhost', $username, $password);
if (!$connection) {
    die('Not connected : ' . mysql_error());
}
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
    die ('Can\'t use db : ' . mysql_error());
}
$lat =$_GET['inputLat']; 
$lng =$_GET['inputLng']; 
$sql = "INSERT INTO sometable (lat, lng) VALUES ('$lat', '$lng')";
if (!mysqli_query($connection,$sql)) {
    die('Error: ' . mysqli_error($connection));
};
mysqli_close($connection);
?>