Google Ajax Libraries Gotcha!

Written on February 23rd, 2010 by Thorno shouts

I was working on Google Map for the past few days, and was using jQuery to retrieve markers information from another URL using ajax. I came across the Google Ajax Libraries (http://code.google.com/apis/ajaxlibs/) which helps to load Javascript from CDN.

Here’s part of the code

//sample code taken from http://code.google.com/apis/ajaxlibs/
<script src="http://www.google.com/jsapi"></script>
<script>
  // Load jQuery
  google.load("jquery", "1");

  // on page load complete, fire off a jQuery json-p query
  // against Google web search
  google.setOnLoadCallback(function() {
    $.getJSON("http://ajax.googleapis.com/ajax/services/search/web?q=google&v=1.0&callback=?",

      // on search completion, process the results
      function (data) {
        if (data.responseData.results &&
            data.responseData.results.length > 0) {
          var results = data.responseData.results;
          
          for (var i=0; i < results.length; i++) {
            // Display each result however you wish
            alert(results[i].titleNoFormatting);
          }    
        }
        
      });
    });
</script>

By using this code, we actually load jQuery 1 from the CDN. However, there is a gotcha. If you follow the example I attached just now, it probably won’t work, well, at least not on my FF3.5 and IE8. In fact, you will have to do something like the following instead
//sample code taken from http://code.google.com/apis/ajaxlibs/
<script src="http://www.google.com/jsapi"></script>
<script>
  // Load jQuery
  google.load("jquery", "1");
</script>
<script>
  // on page load complete, fire off a jQuery json-p query
  // against Google web search
  google.setOnLoadCallback(function() {
    $.getJSON("http://ajax.googleapis.com/ajax/services/search/web?q=google&v=1.0&callback=?",

      // on search completion, process the results
      function (data) {
        if (data.responseData.results &&
            data.responseData.results.length > 0) {
          var results = data.responseData.results;
          
          for (var i=0; i < results.length; i++) {
            // Display each result however you wish
            alert(results[i].titleNoFormatting);
          }    
        }
        
      });
    });
</script>

You will have to close the script tag that load external script from CDN before you can use it. Else you will get javascript error, in IE8, it shows ‘Object expected’.I really hope you will be able to read my article before you pull all your hair off. :)

Happy Coding

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • DZone
  • LinkedIn
  • Live
  • Reddit
Filed under Programming, Work Tags:,

Leave a Reply

(required)

(required)