tags:

views:

891

answers:

2

To all,

I am trying to retrieve the exchange rate from Google with jQuery's $.getJSON(). Using the request: "http://www.google.com/ig/calculator?hl=en&q=1USD=?CAD"

returns a simple JSON file: {lhs: "1 U.S. dollar",rhs: "1.03800015 Canadian dollars",error: "",icc: true}

I am using the following jquery function to get the Canadian dollar amount.:

$(document).ready(function(){
    $.getJSON("http://www.google.com/ig/calculator?hl=en&q=1USD=?CAD?&label=rhs&format=json&jsoncallback=?",
              function(data){
                  alert(data);
              });
});
</script>

Fire bug displays the correct JSON file but indcates that an invalid label is used.

Any help is appreciated.

Bob

+5  A: 

Google returns pure JSON and does not support JSONP (=JSON wrapped in a callback).

JSONP looks like:

callbackFunction({json_object: "some_data"})

The browser can load JSONP-Data from other domains like it can load JavaScript in script-tags from other domains. Pure JSON data cannot be executed as JavaScript and that's why it cannot be loaded inside script-tags from other domains.

In this specific case Google can get the JSON on iGoogle by using simple AJAX (because it's the same domain), but you cannot request it from your domain from inside the browser. You can, however, query it on your server, work with the result there and send it to the client (your server acting as a proxy).

stefanw
Great answer. Can you elaborate on the difference between JSON and JSONP?
Nick Stinemates
Nick,Can I treat the json file as text and parse it myself?Thanks,Bob
Bob Knothe
Hey Bob, you cannot access files from other servers in your browser (same domain policy) if these files are not JavaScript. The only viable solution is to request them directly from your server and send the result to the browser.
stefanw
Nick,PHP it is - just another learn curve.thanks for your helpBob
Bob Knothe
+1  A: 

I don't think Google calculator supports JSONP (which is required for cross-domain javascript). Especially your &jsoncallback=? doesn't do anything.

You need to use a proxy on your server.

Marcel J.
Thanks Marcel,Guess I have to start using PHP.Bob
Bob Knothe