jQuery - 消耗 JSON 资源 - 有些返回数据,有些则不返回。为什么?

标签 jquery ajax json jsonp

我试图弄清楚如何在浏览器中使用 json URL 并使用 DOM 在网页中呈现数据。我没有得到一致或可预测的答复。

我找到了JSON URL at Google Calendar如果我只是在地址栏中输入 URL,它会在浏览器中显示 json 响应。

我找到了另一个JSON URL at business.gov如果我只是在地址栏中输入 URL,它会在浏览器中显示不同的 json 响应。 。

然后,我尝试使用 jQuery 发出 $.ajax 调用来使用和显示这两个 JSON 资源。

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  htmlobj=$.ajax(
            {url:"http://www.google.com/calendar/feeds/developer-calendar@google.com/public/full?alt=json",
             async:false} 
            );

  if (jQuery.isEmptyObject(htmlobj.responseText)===true) {
    alert("htmlobj.responseText is empty");
  } else {
    alert("htmlobj.responseText has stuff in it");
  }

  $("#myDiv").html(htmlobj.responseText).fadeIn();

  htmlobj1=$.ajax(
         {url:"http://api.business.gov/geodata/city_county_links_for_state_of/CA.json",
                async:false, 
                dataType:'text', 
                });

  if (jQuery.isEmptyObject(htmlobj1.responseText)===true) {
    alert("htmlobj1.responseText is empty");
  } else {
    alert("htmlobj1.responseText has stuff in it");
  }

  $("#myGovDiv").html(htmlobj1.responseText).fadeIn();
});
</script>
</head>
<body>
   <h3>Google Calendar - json only</h3>
   <div id="myDiv" style="display:none"></div>

   <h3>Business.Gov</h3>
   <div id="myGovDiv" style="display:none"></div>
</body>

Google 日历 JSON 资源消耗良好,但business.gov JSON 资源甚至没有在响应中返回。 (我检查了 Firebug,它返回了 HTTP 代码 200,响应文本中没有任何内容)。

为什么两个 JSON URL 在浏览器中都返回了良好的 JSON 数据,但 jQuery.ajax 只能使用 Google Calendar URL,而 jQUery.ajax 无法使用business.gov URL?

编辑 - 2010 年 6 月 19 日,美国东部时间 6:36 - 谢谢 @Juan Manuel@TheJuice 。我尝试了 jsonp...这就是我得到的。

如果我将调用更改为以下内容,我可以让浏览器停止阻止来自 api.business.gov 的响应,但我无法获取数据(例如 htmlobj2 为 nil)

  htmlobj2=$.ajax(
        {url:"http://api.business.gov/geodata/city_county_links_for_state_of/CA.json",
         async: false,
         dataType: 'jsonp',
         success: function(data, textStatus) {
            alert("Success");
            $('#myDiv').html("Your data: " );
       },
         error: function ( XMLHttpRequest, textStatus, errorThrown){
                    alert('error');
                }
    }
);

无论我使用“jsonp”还是“script”的数据类型,我都会得到相同的结果。 htmlobj2 为 nil,但响应头具有整个 json 数据字符串。此外,如果我尝试将回调函数绑定(bind)到以“data”作为参数的 .ajax 调用,则该“data”参数也是一个 nil 对象。此外,成功或失败处理程序都不会被调用。

如何从响应字符串中提取此 JSON 数据并将其显示在我的网页上?

编辑 - 2010 年 6 月 22 日上午 11:17

我找到了一个 Ruby 脚本并对其进行了调整以尝试使用 URL。我在交互式 Ruby (irb) 中运行了它。

require 'rubygems'
require 'json'
require 'net/http'

url = "http://api.business.gov/geodata/city_county_links_for_state_of/CA.json"
resp = Net::HTTP.get_response(URI.parse(url))
data = resp.body
result = JSON.parse(data)
result.each{|entry| p entry["name"] + "," + entry["full_county_name"] }

我也能够使用类似的 Ruby 脚本来使用 Google 日历 URL。

底线?我可以使用 Ruby 来使用 JSON 资源(api.business.gov 和 Google Calendar),但只能在浏览器中使用 Javascript/jQuery 来使用 Google Calendar 资源。

如果我能得到任何见解,我将不胜感激。从网络上的任何文档或 API 描述中似乎都不清楚为什么 Google 日历提要无论如何都能在浏览器中工作,但 api.business.gov 提要无法在使用 JSON 或 JSONP 的浏览器中工作。

最佳答案

正如 Juan Manuel 指出的那样,这是您的浏览器,可以保护您免受跨站点脚本攻击。如果您在 Fiddler 中查看您的请求,您可以看到发生了什么。

这是来自 google 的响应 header 的一部分:

HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Access-Control-Allow-Origin: *
Rest Omitted...

这来自business.gov:

HTTP/1.1 200 OK
Date: Fri, 18 Jun 2010 21:52:10 GMT
Server: Mongrel 1.1.4
Status: 200 OK
X-Runtime: 0.36775
ETag: "172ec84fa79f748265e96d467af3d3dd"
Cache-Control: private, max-age=0, must-revalidate
Content-Type: application/json; charset=utf-8
Via: 1.1 api.business.gov
Content-Length: 229427
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Set-Cookie: .....7c5; path=/
Age: 0

[
  {"name": "Adelanto" ,
   "fips_county_cd": "71" ,
   "feat_class": "Populated Place" ,
   "county_name": "San Bernardino" ,
   "primary_latitude": "34.58" ,
   "state_name": "California" ,
..... (rest omited)

您看到 Business.gov 的响应实际上已返回,但被浏览器阻止。

更新您的更新: Google Web 服务正在为您处理 JSONP 和 jQuery。 Business.gov Web 服务显然不支持 JSONP。您将需要使用 Ruby(服务器端代码)充当代理并使用business.gov 服务,然后将响应返回给客户端。

关于jQuery - 消耗 JSON 资源 - 有些返回数据,有些则不返回。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3072682/

相关文章:

javascript - 在页面上找到重复的 div ID 名称并使用 Javascript 或 jQuery 附加一个数字

javascript - 使用ajax从html输入>日期保存值

javascript - Express.js模板引擎,可以呈现JSON和未转义的字符串

json - 如何将 HL7 v2.x 消息转换为 FHIR JSON?

javascript - Jquery 延迟。多个 ajax 调用。延迟与异步假

javascript - Jquery,在其父限制内打开div

javascript - 从 javascript 访问 django url

c# - 从 JSON 创建数组

php - 如何在不刷新的情况下在页面上获得实时信息?

javascript - 如何在getcontenttools库中通过jquery发送ajax