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 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作