我正在尝试使用获取 Google map 脚本的 $.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/