dounaidu0204 2014-01-23 11:44
浏览 52
已采纳

无法从PHP检索AJAX数据

I'm trying to create a simple application that finds your location, sends the co-ordintes using AJAX to a PHP file and then calculates distances in the PHP to show nearby shops.

this is my Javascript and ajax:

$(document).ready(function($) {

// Check for GEOLOCATION support 
if (navigator.geolocation) {
window.onload = function() {
var startPos;
var lat;
var lon;
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById('currentLat').innerHTML = startPos.coords.latitude;
document.getElementById('currentLon').innerHTML = startPos.coords.longitude;
drawMap(startPos);
}, 

function(error) {
document.getElementById('locationSupport').innerHTML = "Error code: " + error.code;
                            //   0 unknown error
                            //   1 permission denied
                            //   2 position unavailable (error response from locaton provider)
                            //   3 timed out
                        });
                    };
                }
                else {
                    document.getElementById("locationSupport").innerHTML = 'Geolocation is not supported.';
                }
            }); 

function drawMap(position) {
    var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var mapOptions = {
        zoom: 15,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);
    var userMarker = new google.maps.Marker({position: myLatLng, map: map});
    }       

     var jQT = new $.jQTouch({
                statusBar: 'black-translucent',
                useFastTouch: false, //required for Android
                preloadImages: []
            });

$.ajax({
   type     : "POST",
   url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/location.php",
   data : {lat: 'lat', lon: 'lon'},
   dataType : "text",
   success: function(data){
     $("#shopsnotification").html(data);
   }
});   

and then in my PHP I am using:

<?php 
    $str_shopresult = '';
    mysqli_select_db($db_server, $db_database);
    $lat = $_POST['lat'];
    $lon = $_POST['lon'];
    $query = "SELECT name, address, 
    (6378.10 * ACOS(COS(RADIANS(latpoint)) * COS(RADIANS(lat)) * COS(RADIANS(longpoint) - RADIANS(lng)) + SIN(RADIANS(latpoint)) * SIN(RADIANS(lat)))) 
    AS distance FROM shops JOIN (SELECT '$lat' AS latpoint, '$lon' AS longpoint) AS p ORDER BY distance LIMIT 10"; 
    $result = mysqli_query($db_server, $query); 
        if (!$result) die("Database access failed: " . mysqli_error($db_server)); 
        while($row = mysqli_fetch_array($result)){ 
    $str_shopresult .= "<strong>" . $row['name']  . "</strong><br>" .
    $row['address'] . "<br><br>"; 
 } 

mysqli_free_result($result); 
echo $str_shopresult; 
mysqli_close($db_server); 
?> 

Can anyone see why this isn't working? It just seems to be displaying the shops in a random order rather than using the $lat and $lon variables. Am I retrieving the data wrong? the ajax is displaying the data therefore should be sending the variables correctly (I think)

Any help would be greatly appreciated!

  • 写回答

2条回答 默认 最新

  • doufuxi7093 2014-01-23 11:57
    关注

    Send the values as suggested by KSDaemon and in addition to that, move your $.ajax method to the end of navigator.geolocation.getCurrentPosition success method. Otherwise it might get executed before the page is ready and the lat and lon values have been populated.

    $(document).ready(function ($) {
    
      // Check for GEOLOCATION support 
      if (navigator.geolocation) {
        window.onload = function () {
          var startPos;
          var lat;
          var lon;
          navigator.geolocation.getCurrentPosition(function (position) {
              startPos = position;
              lat = startPos.coords.latitude;
              lon = startPos.coords.longitude;
              document.getElementById('currentLat').innerHTML = startPos.coords.latitude;
              document.getElementById('currentLon').innerHTML = startPos.coords.longitude;
              drawMap(startPos);
    
              $.ajax({
                type: "POST",
                url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/location.php",
                data: {
                  lat: lat,
                  lon: lon
                },
                dataType: "text",
                success: function (data) {
                  $("#shopsnotification").html(data);
                }
              });
            },
    
            function (error) {
              document.getElementById('locationSupport').innerHTML = "Error code: " + error.code;
              //   0 unknown error
              //   1 permission denied
              //   2 position unavailable (error response from locaton provider)
              //   3 timed out
            });
        };
      } else {
        document.getElementById("locationSupport").innerHTML = 'Geolocation is not supported.';
      }
    });
    
    function drawMap(position) {
      var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
      var lat = position.coords.latitude;
      var lon = position.coords.longitude;
      var mapOptions = {
        zoom: 15,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }
    
      var map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);
      var userMarker = new google.maps.Marker({
        position: myLatLng,
        map: map
      });
    }
    
    var jQT = new $.jQTouch({
      statusBar: 'black-translucent',
      useFastTouch: false, //required for Android
      preloadImages: []
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化