jQuery getScript 返回解析错误异常

标签 jquery ajax google-maps getscript

我正在尝试使用获取 Google map 脚本的 $.getScript 函数加载两个脚本,然后加载后,我会得到另一个脚本 ( goMap ),这使得 map 小程序变得容易待制作。

但是,加载时,获取 Google Map API 的第一个脚本正常,然后第二个脚本返回解析错误并显示以下内容:

TypeError: 'undefined' is not a constructor'

但是,我不知道它是从哪里引用的或哪一行,我认为它一定是尝试在此文件上执行地理编码器((function($){ 之后的第一行:

http://www.pittss.lv/jquery/gomap/js/jquery.gomap-1.3.2.js

这是我的代码:

$.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/

相关文章:

javascript - 在javascript中生成一个列表并将其添加到html中的div

javascript - Google map 自动完成列表

iphone - 是否可以跟踪 ios 设备?

java - Android 多个标记未在 map 上绘制

jquery - 如何在 jQuery 中通过滚动使背景图像淡入淡出?

javascript - 如何在ejs模板中的for循环内为每个html元素创建唯一的id?

jquery - 根据 CSV 中的值检查复选框

javascript - 动态 html 内容

php - 访客客户检查 Woocommerce 订单账单电子邮件时可享受首单折扣

php - 为 jquery + php 创建永久链接