我正在尝试使用 $.getScript
加载两个脚本获取谷歌地图脚本的功能,然后在加载之后,我得到另一个脚本( goMap
),它可以轻松制作 map 小程序。
但是,加载后,获取 Google Map API 的第一个脚本很好,然后第二个脚本返回解析错误并显示如下:
TypeError: 'undefined' is not a constructor'
但是,我不知道它是从哪里引用或从哪一行引用的,我认为它一定是试图在这个文件上执行地理编码器(
(function($){
之后的第一行:这是我的代码:
$.getScript('http://maps.google.com/maps/api/js?sensor=true').done(function()
{
$.getScript('../js/gomap.js').done(function()
{
// this never gets called
alert('gomap loaded');
}).fail(function(jqxhr, settings, exception)
{
alert(exception); // this gets shown
});
}).fail(function()
{
alert('failed to load google maps');
});
我尝试更改 AJAX 设置以设置
async
至false
,但它根本没有帮助。
最佳答案
该错误是由于 Google Maps API 期望在头部加载,使用 <script src="http://maps.google.com/maps/api/js?sensor=true"></script>
.
如果由于某种原因你不能做到这一点,那么仍然有希望。 Google Maps API 不起作用,因为它使用 document.write
在页面中注入(inject)依赖项。要使代码正常工作,您可以覆盖 native document.write
方法。
演示:http://jsfiddle.net/ZmtMr/
var doc_write = document.write; // Remember original method;
document.write = function(s) {$(s).appendTo('body')};
$.getScript('http://maps.google.com/maps/api/js?sensor=true').done(function() {
$.getScript('../js/gomap.js').done(function() {
alert('gomap loaded');
document.write = doc_write; // Restore method
}).fail(function(jqxhr, settings, exception) {
alert(exception); // this gets shown
document.write = doc_write; // Restore method
});
}).fail(function() {
alert('failed to load google maps');
});
关于jQuery getScript 返回解析错误异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343666/