Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

ajax - jQuery getScript returns an parse error exception

I'm trying to load two scripts with the $.getScript function of getting Google Map script, then after that is loaded, I get another script (goMap) which makes map applets easily to be made.

However, when loaded, the first script of getting Google Map API is good, then the second script returns a parse error and shows this:

TypeError: 'undefined' is not a constructor'

Yet, I don't know where that is referencing from or which line, I think it must be trying to execute the Geocoder on this file (first line after (function($){:

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

Here is my code:

$.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');
});

I tried changing the AJAX settings to set async to false, but it didn't help at all.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The error is caused by the fact that the Google Maps API expects to be loaded in the head, using <script src="http://maps.google.com/maps/api/js?sensor=true"></script>.

If you cannot do that for some reason, there's still hope. The Google Maps API does not work, because it uses document.write to inject a dependency in the page. To get the code to work, you can overwrite the native document.write method.

Demo: 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');
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...