我正在尝试编写一个脚本,将地理位置的纬度和经度作为数组传递给 PHP,并使用 jQuery AJAX 将值返回到客户端。我能找到的最好的解决方案是 JSON。由于某种我无法判断的原因,我的以下脚本返回了 NULL
值。
index.html
<div id="geoloc"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$('#geoloc').html("<p>Geolocation is not supported by this browser</p>");
}
function showPosition(position) {
var latlng = [ {"lat":position.coords.latitude, "lng":position.coords.longitude}];
$.ajax({
type: "POST",
url: "libs/filterstores.php",
data: { json: JSON.stringify(latlng) },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
$('#geoloc').html("Latitude: " + data.lat + "<br />Longitude: " + data.lng);
}
});
}
});
</script>
filterstores.php
$currloc = json_decode($_POST['latlng'], true);
$stores = array('lat'=>$currloc['lat'],'lng'=>$currloc['lng']);
echo json_encode($stores);
以下是我点击浏览器中弹出的“共享位置”按钮后得到的返回结果
Latitude: sdf
Longitude: sdfsd
最佳答案
应该这一行:
data: { json: JSON.stringify(latlng) },
未指定currloc作为参数?
即
data: { currloc: JSON.stringify(latlng) },
关于php - AJAX、JSON 和 PHP 返回值问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18009709/