duan20145 2015-12-20 11:05
浏览 175
已采纳

基于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>
  • 写回答

2条回答 默认 最新

  • dpq755012465 2015-12-20 12:32
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类