3

当回调是全局函数时,我只能下载 Google Maps v3 API:

function onMapLoad() {
    alert('API is loaded');
}

var script = new Element(
    'script', {
        type: 'text/javascript',
        src: 'http://maps.googleapis.com/maps/api/js?key=' 
            + Map.API_KEY
            + '&sensor=false&callback=onMapLoad'
    }
);

document.body.appendChild(script);

我不想使用全局函数。相反,我想在单例上调用一个方法:Map.instance().onLoaded

// ...
+ '&sensor=false&callback=Map.instance().onLoaded'
// ...

当我尝试这样做时,会出现 NetworkError: 403 Forbidden on loading Google's scripts。这似乎暗示谷歌的服务不喜欢我的回调函数字符串。回调函数本身没有问题。

4

2 回答 2

0

It looks like Google doesn't like the function call () part of your callback string, but it doesn't have any issues with the fact that it's not global on the document.

I too get a 403 on this:

http://maps.googleapis.com/maps/api/js?key=4&sensor=false&callback=Map.mapLoaded%28%29

But not this:

http://maps.googleapis.com/maps/api/js?key=4&sensor=false&callback=Map.instance.mapLoaded

Seems like if you could just specify a function property of the Map object for the callback instead of the return value of the instance() function, you can avoid the extra global. I didn't see anything regarding this in their API, but I didn't spend too long looking into that.


I haven't had to use JSONP tactics in a long while, so I wasn't sure if this was a limitation of JSONP requiring callbacks to be global or just something that Google was imposing. It seems to be a Google-only thing, as this JSONP test site seems to have no issues with the parens as the response and fiddle show:

http://date.jsontest.com/?callback=Map.foo%28%29

Fiddle: http://jsfiddle.net/6WawP/

Hope this helps

于 2012-10-04T04:40:50.183 回答
0

尝试使用 google loader 调用

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

google.load("maps", "3", {"other_params": "sensor=false","callback" : Map.instance().onLoaded });

https://developers.google.com/loader/

于 2012-10-06T06:59:49.363 回答