php - AJAX、JSON 和 PHP 返回值问题

标签 php ajax json

我正在尝试编写一个脚本,将地理位置的纬度和经度作为数组传递给 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/

相关文章:

javascript - 使用带有 href 的 ajax 打开动态 php 页面,无需刷新页面

Java - 如何获取 JSON 数组中的对象值?

javascript - 将 PHP 数组转换为 JSON 时动态转义撇号

php - Paypal 订阅问题

php - CORS 预检请求未通过访问控制检查 : It does not have HTTP ok status

javascript - 带有预检请求的 CORS post

JavaScript 数组不使用 Ajax 发布到 PHP 文件

ios - WS Websocket 是否能够在 Swift 中发送或接收 json 对象?

php - 如何创建 API

php - 如何管理许可以启用 Web 应用程序的功能?