问题使用jQuery做一个谷歌地图API调用(JSON不被返回) [英] Issue using jQuery to do a google maps api call (JSON not being returned)

查看:126
本文介绍了问题使用jQuery做一个谷歌地图API调用(JSON不被返回)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我最初使用的代码,直到昨天才正常工作(这是我注意到它的时候,但我不确定它何时确实停止工作)。我知道这是在上周初开始工作,所以在此之间和昨天之间的某个时候它破裂了。我在称为Alpha Anywhere的RAD中运行此代码,但已在此程序之外(仅在HTML页面中)对其进行了测试,但仍无效。希望有人知道是否有错误,或者有什么我可以做的解决这个问题。我用firebug在firefox中运行了这个,并且在那里我看到了让我知道JSON没有被检索到的错误。

  var $ jq = jQuery.noConflict(); 

$ jq.getJSON('http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false',function(results){

//我有代码在这里计算每个状态的行驶里程数
//(如上面的代码原点和目的地将被填充
//变量,但我去了与这个基本的电话,因为即使这不起作用)。

});






以下代码不起作用现在在2013年11月11日下午10:26 CDT)时运行它在Firefox或铬。随着萤火虫它显示我没有得到谷歌的回应。但是,下面的代码在Mac OS X 10.9上的safari 7.0.x中运行时会有响应。


< html>
< head>
< script src =http://api.jquery.com/jquery-wp-content/themes/jquery/js/jquery-1.9.1.min.js>< / script>
< script>
function getData(){
var url ='http://maps.googleapis.com/maps/api/directions/json?origin=Huntsville,AL&destination=Atalanta,GA&sensor=false ;
var $ jq = jQuery.noConflict();
$ jq.getJSON(url,function(results){
alert(results.routes [0] .legs [0] .distance.value);
});
}
< / script>
< title> Google API的jQuery调试< / title>
< meta charset =UTF-8>
< meta name =viewportcontent =width = device-width>
< / head>
< body>
< button onclick =getData();>点击< / button>
< / body>
< / html>


解决方案

这里有几个问题:



首先,从 jsonp解释您可能已经注意到您无法直接从另一个域加载数据文件 。这是一个长期存在的安全问题,通常通过API,REST等共享数据来解决。 然而有一些解决方法 ... [例如] JSONP


在jQuery中执行此操作:



这表明我们要使用 JSONP 。删除它并使用vanilla JSON请求;这将因同源策略而失败。






另一个问题是某些外部API(如 Google地图 Directions API ),不会自动提供JSONP。如果服务器不知道如何处理回调参数,那么API的响应仍然是JSON,而不是JSONP。为了确保返回的内容格式正确,您可以通过代理服务器,如 jsonp.guffa.com < a>



要使用它,请将请求更改为 http://jsonp.guffa.com/Proxy.ashx?url= YourEncodedURI

您将 YourEncodedURI 替换为要求编码的位置 b
$ b lang-js prettyprint-override> var mapsUrl ='http://maps.googleapis.com/maps/api/directions/json'+
'?origin = Toronto& destination =蒙特利尔&安培;传感器=假';
var encodedUrl = encodeURIComponent(mapsUrl);
var proxyUrl ='http://jsonp.guffa.com/Proxy.ashx?url='+ encodedUrl;

$ .ajax({
url:proxyUrl,
dataType:'jsonp',
cache:false,
success:function(data){
console.log(data);
}
});



在jsFiddle中进行工作演示






延伸阅读:


This is the code I was originally using and worked perfectly fine up until yesterday (which is when I noticed it but I am unsure when it actually stopped working for sure). I know this was working at the beginning of last week so sometime between then and yesterday it broke. I am running this code within a RAD called Alpha Anywhere but have tested it outside of this program (in just a HTML page) and it still didn't work. Hoping someone knows if there is a bug or if there is something I can do to fix this issue. I ran this in firefox with firebug on and that is where I saw the error letting me know that the JSON wasn't retrieved.

var $jq = jQuery.noConflict();

$jq.getJSON('http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false',function(results){

    // I have code in here to calculate miles driven per state 
    // (as in the above code origin and destination would be filled 
    // with variables but I went with this basic call because even this doesn't work).

});


This following code does not work (as of right now November 11, 2013 at 10:26 PM CDT) when running it in firefox or chrome. With firebug on it shows I am not getting a response from google. However this following code does respond when ran in safari 7.0.x on Mac OSX 10.9.

<!DOCTYPE html>
<html>
    <head>
        <script src="http://api.jquery.com/jquery-wp-content/themes/jquery/js/jquery-1.9.1.min.js"></script>
        <script>
            function getData() {
                var url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Huntsville,AL&destination=Atalanta,GA&sensor=false';
                var $jq = jQuery.noConflict();
                $jq.getJSON(url, function (results) {
                    alert(results.routes[0].legs[0].distance.value);
                });
            }
        </script>
        <title>jQuery Debug of Google API</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <button onclick="getData();">click</button>
    </body>
</html>

解决方案

There are a couple problems here:

First, from jsonp explained:

As you may be aware you cannot directly load data files from another domain. This is a security issue that has been around for a long time and is commonly solved by sharing data through an API, REST or such. However there are ways around this ... [for example] JSONP

To do this in jQuery:

That indicates that we want to use JSONP. Remove it and a vanilla JSON request will be used; which will fail due to the same origin policy.


Another issue is that some external APIs (like Google Maps Directions API), don't automatically serve JSONP. If the server doesn't know what to do with the callback parameter then the response from the API will still be JSON, not JSONP. In order to ensure the returned content is formatted correctly, you can go through a proxy server like the jsonp.guffa.com

To use it, change the request to http://jsonp.guffa.com/Proxy.ashx?url=YourEncodedURI
Where you have replaced YourEncodedURI with the encoded requested url string.


Putting it all together:

var mapsUrl    = 'http://maps.googleapis.com/maps/api/directions/json' + 
                 '?origin=Toronto&destination=Montreal&sensor=false';
var encodedUrl = encodeURIComponent(mapsUrl);
var proxyUrl   = 'http://jsonp.guffa.com/Proxy.ashx?url=' + encodedUrl;

$.ajax({
    url: proxyUrl,
    dataType: 'jsonp',
    cache: false,
    success: function (data) {
        console.log(data);
    }
});

Working Demo in jsFiddle


Further Reading:

这篇关于问题使用jQuery做一个谷歌地图API调用(JSON不被返回)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆