如何在PHP中使用Ajax $ _POST从javascript中检索位置数据?

时间:2015-07-10 22:01:13

标签: javascript php ajax post location

我无法在PHP中使用以下代码。我想检索用户位置,然后将其发送到我的PHP脚本,以便在服务器上进一步处理。 Php不会检索数据。

编辑:

    <!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>


<script>

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  } else {
  alert('Geolocation is required for this page, but your browser doesn&apos;t support it. Try it with a browser that does, such as Opera 10.60.');
}

function successFunction(position) {
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  var latlong = {"lat" : lat , "long" : long};
  var latlong_encoded = JSON.stringify(latlong);

  $.ajax({
   url: 'PostTest.php',
   type: 'POST',
   data: {"userLocation" : latlong_encoded},
   success: function(data) {
        alert(latlong_encoded);
   }
});

}

function errorFunction(position) {
  alert('Error!');
}
</script>


</body>
</html>

这是php代码:

<?php
$lat[]= array('coord'=>json_decode($_POST["userLocation"]));
print_r($lat);
?>

我只是得到一个空数组。 数组([0] =&gt;数组([coord] =&gt;))

1 个答案:

答案 0 :(得分:0)

尝试添加

dataType: "json" //for response
contentType: "application/json; charset=UTF-8" //for request
在ajax请求中

..

我的片段:

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showLocation);
    }
    else { 
    alert('Geolocation non supported..');
    }

    function showLocation(position) {
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
        $.ajax({
           //YOUR AJAX REQUEST USING LAT, LONG
        });
    }