Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.getJSON( url, [data], [callback] )

Tags:

jquery

getjson

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 indicates that an invalid label is used.

like image 366
Bob Knothe Avatar asked Oct 18 '09 20:10

Bob Knothe


2 Answers

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).

like image 125
stefanw Avatar answered Oct 10 '22 09:10

stefanw


In addition to the cross-domain problem, the data you received is not valid JSON. The keys need to be quoted. I think that's why Firebug tells you invalid labels are used.

// this fails
jQuery.parseJSON('{lhs: "1 U.S. dollar", rhs: "1.03800015 Canadian dollars", error: "", icc: true}'));

// this works
jQuery.parseJSON('{"lhs": "1 U.S. dollar", "rhs": "1.03800015 Canadian dollars", "error": "", "icc": true}'));
like image 45
netvope Avatar answered Oct 10 '22 09:10

netvope