基于Javascript函数值,通过PHP检索数据库数据

I am getting a place name to this file using GET. Then I am converting the place name into latitude and longitude.

I want to display some data from the database, based on the latitude and longitude, but I am unable to send the latitude and longitude variables from JS to PHP.

I also tried Ajax, but that also didn't work, because PHP loads before the script. Correct me if I am wrong.

Any kind of help will be appreciated.

<?php
    $user_latitude
    $user_longitude
    $result=$con->query("SELECT *, ( 6371 * acos( cos( radians($user_latitude) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians($user_longitude) ) + sin( radians($user_latitude) ) * sin( radians( lat ) ) ) ) AS distance FROM Location HAVING distance < 100 ORDER BY distance LIMIT 0 , 10");

    for($x=0;$x<$result->num_rows;$x++){
        $row=$result->fetch_assoc();
        echo "<div class='result-data'>";
        echo $row["name"];
        echo "</div>";
        }
    ?>
<script>
$(function() {  
    geocoder = new google.maps.Geocoder();
    alert($_GET('location'));
    var address = $_GET('location');
    address=address+',Delhi,India';
    alert(address);
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        latitude=results[0].geometry.location.lat();
        longituderesults[0].geometry.location.lng();
        alert("Latitude: "+results[0].geometry.location.lat()+latitude);
        alert("Longitude: "+results[0].geometry.location.lng()+longitude);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  });

  function $_GET(param) {
    var vars = {};
    window.location.href.replace( 
    /[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
    function( m, key, value ) { // callback
        vars[key] = value !== undefined ? value : '';
    }
  );
  if (param) {
    return vars[param] ? vars[param] : null;    
  }
  return vars;
}   
</script>

Going to have to use AJAX to be able to achieve your desired result for this one. Due to the order of operations that need to be executed, I can't see another way around it.

Here's some example code for you, you'll also need to split your code into two files.

file1.php (using jQuery AJAX, hope that's OK)

<?php
if(isset($_GET)){
    $location = $_GET['l'];
}
?>

<div id="test"></div>

<script>
    $(function() {

        geocoder = new google.maps.Geocoder();

        alert('<?=$location?>');
        var address = '<?=$location?>';
        address=address+',Delhi,India';
        alert(address);
        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();

                alert("Latitude: "+results[0].geometry.location.lat()+latitude);//Both of these would be the same?
                alert("Longitude: "+results[0].geometry.location.lng()+longitude);
                $.ajax (
                    {
                        type    :   "POST",
                        url     :   "file2.php",
                        data    :
                        {
                            longitude:longitude,
                            latitude:latitude
                        },
                        success :   function(result)
                        {
                            $('#test').html(result);
                        },
                        error: function (xhr, ajaxOptions, thrownError)
                        {
                            alert(xhr.status);
                            alert(thrownError);
                        }
                    });

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

    });
</script>

Note you were missing = for you longitude variable declaration.

file2.php (this is the file ajax will request and then pull down the data)

<?php
//connection to your DB here
$user_latitude = $_POST['latitude'];
$user_longitude = $_POST['longitude'];

$result=$con->query("SELECT *, ( 6371 * acos( cos( radians($user_latitude) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians($user_longitude) ) + sin( radians($user_latitude) ) * sin( radians( lat ) ) ) ) AS distance FROM Location HAVING distance < 100 ORDER BY distance LIMIT 0 , 10");

for($x=0;$x<$result->num_rows;$x++){
    $row=$result->fetch_assoc();
    echo "<div class='result-data'>";
    echo $row["name"];
    echo "</div>";
}

This way the location name will be loaded with $_GET from the URL (something like mysite.com/file1.php?l=delhi) and passed to JS, AJAX call then made to the php file that requests the data from the DB. Then finally this is displayed in the id=test div.

This should work but there are some security concerns with $_GET you should be aware of. http://www.ultramegasoft.com/blog/2009/08/5-basic-php-security-tips/ Also a ton of information about $_GET on SO. I wouldn't use the above code in production without some tightening. This method with also chain your JS to PHP which is not ideal.

$_GET is a php function, so calling it inside your JavaScript won't work. You need to use something like: http://api.jquery.com/jquery.ajax/ and setup an endpoint on your server to deal with the ajax request.