使用 jQuery 解析 Google Geo API(反向地理编码)
我确信我不是唯一的一个,但是当 jQuery 接受查找地址的请求时,当请求的数据是纬度和经度时,我无法解析/返回任何内容code> 这样 Google 可以返回数据,但 jQuery 无法读取?
http://maps.googleapis.com/maps/api/geocode/json
带参数:
latlng=51.276914,1.077252
&sensor=false
在 Firebug 中,它显示 200 OK
但响应中没有显示任何内容:
我所做的是:
$.ajax(
{
url: 'http://maps.googleapis.com/maps/api/geocode/json',
data: 'latlng=' + geolocation + '&sensor=false',
dataType: 'json',
cache: false,
success: function(data){ alert(data); }
});
那不是不起作用... $.get
、$.getJSON
和 json
dataType
都不起作用。
为什么 jQuery 无法解析/读取响应?
I'm sure I'm not the only one, but I cannot parse/return anything when jQuery takes a request to lookup an address when the data being requested is the latitude
and longitude
so Google can return the data, but it cannot be read by jQuery?
http://maps.googleapis.com/maps/api/geocode/json
With parameters:
latlng=51.276914,1.077252
&sensor=false
In Firebug it says 200 OK
but nothing is displayed in the response:
I can see it when I open it: http://maps.googleapis.com/maps/api/geocode/json?latlng=51.187296,1.229086&sensor=false&_=1302084865163
What I did was:
$.ajax(
{
url: 'http://maps.googleapis.com/maps/api/geocode/json',
data: 'latlng=' + geolocation + '&sensor=false',
dataType: 'json',
cache: false,
success: function(data){ alert(data); }
});
That doesn't work... neither $.get
, $.getJSON
with the json
dataType
.
Why can't jQuery parse/read the response?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
出于安全原因,您需要使用谷歌地理编码器。请参阅此处的答案。
You need to use googles geocoder for security reasons. See answer here.
正如 Bjorn 上面所指出的,由于端点位于不同的域上,因此存在安全限制。然而,您不需要使用地理编码器,因为它所做的只是发出 ajax 请求 - 它所做的只是您现在正在做的事情。
正如 Shidhin Cr 上面所指出的,解决安全问题的一种方法是您可以附加callback=?,但真正要做的只是执行 jQuery 可以通过使用“jsonp”dataType 参数自动为您执行的任务。
另外,如果您使用 $.getJSON,它应该会自动注意到这是在远程服务器上,并自动为您将请求升级到 jsonp - 但我可能记得错误,有一些关于与该特定调用相关的 jquery 文档的参数。
无论哪种情况,上述建议都是正确的,只是缺乏细节。
As noted above by Bjorn there are security constraints due to the endpoint being on a different domain. However you do NOT need to use geocoder, as all that does is make an ajax request - it does little more than what you are doing now.
As Shidhin Cr notes above, one way around the security problem is that you can append callback=?, but all that really is doing is performing a task that jQuery can do for you automatically by using the "jsonp" dataType argument.
Also if you use $.getJSON it should automatically note that this is on a remote server and upgrade the request to jsonp automatically for you - but I might be remembering that wrong, there were some arguments about the jquery documentation related to that particular call.
In either case both of the above suggestions are correct, they were just lacking detail.
像这样更改数据参数。你可以看到响应正常
Change the data parameter like this . you can see the response coming properly
尝试使用 $.getJSON 来获取结果
示例
try use $.getJSON to get the result
Example