我在解析 JSON 响应时遇到了麻烦。我已经这样做了很多次,但这不起作用,原因我无法辨别。这是我正在做的事情:
在任何人提出建议之前 - 由于我正在处理的项目的一些要求,我必须使用服务器端的谷歌地理编码网络服务,我不能在客户端做这一切。
我将 PHP 用于服务器端部分。我正在使用 AJAX(通过 jQuery)将位置发送到服务器,获取响应并将其返回编码为 JSON。这是服务器端代码:
<?php
if(!empty($_POST['theLocation']))
{
$loc = urlencode($_POST['theLocation']);
$response = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=$loc,+CA&sensor=false");
echo json_encode($response);
}
?>
这是客户端调用,其中 theLocation 是位置名称:
var postdata = "theLocation=" + encodeURIComponent(theLocation);
$.ajax( {
type : "POST",
url : "GeoEncode.php",
data :postdata ,
dataType : "JSON",
success : function(data) {
data = $.parseJSON(data);
lat = data.results[0].geometry.location.lat;
lng = data.results[0].geometry.location.lng;
},
error: function (request, status, error) {
log("Error: getLatLong Status - " + status + " ErrorText - " + error);
}
});
当我尝试访问时,data.results[0]
我得到了错误Uncaught TypeError: Cannot read property '0' of undefined
。这显然意味着没有结果属性。但是,如果我这样做,console.log(data)
这就是我得到的:
{
"results": [
{
"address_components": [
{
"long_name": "Halifax",
"short_name": "Halifax",
"types": [
"locality",
"political"
]
},
{
"long_name": "Halifax",
"short_name": "Halifax",
"types": [
"administrative_area_level_3",
"political"
]
},
{
"long_name": "Halifax Regional Municipality",
"short_name": "Halifax Regional Municipality",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "Nova Scotia",
"short_name": "NS",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "Canada",
"short_name": "CA",
"types": [
"country",
"political"
]
}
],
"formatted_address": "Halifax, NS, Canada",
"geometry": {
"bounds": {
"northeast": {
"lat": 44.7035312,
"lng": -63.55963089999999
},
"southwest": {
"lat": 44.5949302,
"lng": -63.68627009999999
}
},
"location": {
"lat": 44.6488625,
"lng": -63.5753196
},
"location_type": "APPROXIMATE",
"viewport": {
"northeast": {
"lat": 44.7035312,
"lng": -63.55963089999999
},
"southwest": {
"lat": 44.5949302,
"lng": -63.68627009999999
}
}
},
"types": [
"locality",
"political"
]
}
],
"status": "OK"
}
这是有效的 JSON,显然有一个 results 属性。我不知道为什么我会遇到这个问题,我一定是遗漏了一些东西,但是通过我的调试我还没有找到什么。如果有人可以提供任何建议,将不胜感激。谢谢!