jQuery.getJSON( url, [data], [callback] )
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 开发者_如何学Ca 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.
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).
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}'));
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.
精彩评论