无法从PHP检索AJAX数据

时间:2014-01-23 11:44:02

标签: javascript php jquery ajax

我正在尝试创建一个找到您的位置的简单应用程序,使用AJAX将坐标发送到PHP文件,然后在PHP中计算距离以显示附近的商店。

这是我的Javascript和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);
   }
});   

然后在我的PHP中使用:

<?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); 
?> 

任何人都可以看到为什么这不起作用?它似乎是以随机顺序显示商店而不是使用$ lat和$ lon变量。我检索数据错了吗? ajax正在显示数据,因此应该正确发送变量(我认为)

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

您要在strings中发送data : {lat: 'lat', lon: 'lon'},,而不是在值中发送data : {lat: lat, lon: lon}, 。 你应该把它改成

data : {"lat": lat, "lon": lon}

{{1}}

答案 1 :(得分:0)

按照KSDaemon的建议发送值,除此之外,将$.ajax方法移至navigator.geolocation.getCurrentPosition成功方法的末尾。否则,它可能会在页面准备好之前执行,并且已经填充了lat和lon值。

$(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: []
});