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

如何在PHP中使用Ajax$\u POST从javascript检索位置数据?,javascript,php,ajax,post,location,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 (navi

我无法让以下代码在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>

if(导航器.地理位置){
navigator.geolocation.getCurrentPosition(successFunction,errorFunction);
}否则{
警报('此页面需要地理位置,但您的浏览器不支持它。请使用支持地理位置的浏览器(如Opera 10.60');
}
功能成功功能(位置){
var lat=位置坐标纬度;
var long=位置坐标经度;
var latlong={“lat”:lat,“long”:long};
var latlong_encoded=JSON.stringify(latlong);
$.ajax({
url:'postest.php',
键入:“POST”,
数据:{“用户位置”:latlong_encoded},
成功:功能(数据){
警报(latlong_编码);
}
});
}
功能错误功能(位置){
警报('错误!');
}
以下是php代码:

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

我只得到一个空数组。 数组([0]=>数组([coord]=>)

尝试添加

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

“Php不会检索数据”如何?javascript没有问题-问题要么在
Dataprocessing.Php
,要么,如果这是
Dataprocessing.Php
,您错误地认为发布到
Dataprocessing.Php
会导致底部的Php片段做任何事情。我尝试了两种方法。最初有两个不同的脚本,其中php是Data Processing.php。因为这不起作用,我试着把它全部放在一个脚本中。我想那是错误的方法。但这两种方法都不起作用,在PHP中,您将$lat定义为一个数组两次。从仍不工作的$LAT中删除[]。当我添加数据类型时,成功函数警报不再出现。然后尝试添加contentType:“application/json;charset=UTF-8”。成功函数现在可以工作,但Php似乎没有收到它。php设置中是否有需要更改的内容?是否从$lat中删除了[]?你说什么了吗?检查数据是否发送到php(chrome developer tools中的网络选项卡)。控制台中没有错误,是的,我删除了[]