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

查看:109
本文介绍了jQuery.getJSON(url,[data],[callback])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery的$.getJSON()从Google检索汇率.使用请求:"http://www.google.com/ig/calculator?hl=en&q=1USD=?CAD"

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"

返回一个简单的JSON文件:

returns a simple JSON file:

{
  lhs: "1 U.S. dollar",
  rhs: "1.03800015 Canadian dollars",
  error: "",
  icc: true
}

我正在使用以下jQuery函数来获取加元金额:

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显示正确的JSON文件,但表明使用了无效的标签.

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

推荐答案

Google返回纯JSON,但不支持JSONP(=封装在回调中的JSON).

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

JSONP看起来像:

JSONP looks like:

callbackFunction({json_object: "some_data"})

浏览器可以从其他域加载JSONP数据,就像可以在其他域的脚本标签中加载JavaScript一样.纯JSON数据无法作为JavaScript执行,因此无法将其加载到其他域的脚本标签中.

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.

在这种特定情况下,Google可以使用简单的AJAX在iGoogle上获取JSON(因为它是同一个域),但是您无法从浏览器内部的域中请求它.但是,您可以在服务器上查询它,在其中处理结果,然后将其发送到客户端(您的服务器充当代理).

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

这篇关于jQuery.getJSON(url,[data],[callback])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆