代码之家  ›  专栏  ›  技术社区  ›  Jay Godse

jquery-消耗json资源-一些返回数据,其他不返回。为什么?

  •  3
  • Jay Godse  · 技术社区  · 14 年前

    我正在尝试解决如何在浏览器中使用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>
    

    谷歌日历的json资源消耗得很好,但business.gov json资源甚至没有在响应中恢复。(我检查了firebug,它返回了HTTP代码200,响应文本中没有任何内容)。

    这两个JSON URL在浏览器中都返回了良好的JSON数据,但jquery.ajax只能使用Google日历URL,而jquery.ajax不能使用business.gov URL?

    编辑-2010年6月19日,东部时间6:36 -谢谢 @Juan Manuel @TheJuice . 我试过JSONP…这是我得到的。

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

      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为零,但响应头具有整个JSON数据字符串。此外,如果我试图用“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脚本来使用谷歌日历的URL。

    底线?我可以使用Ruby同时使用JSON资源(api.business.gov和google calendar),但在我的浏览器中只有使用javascript/jquery的google日历资源。

    我很感激能得到任何见解。从网站上的任何文档或API描述中似乎都不清楚为什么Google日历源在浏览器中工作,不管是什么,但是api.business.gov源在使用json或jsonp的浏览器中不工作。

    3 回复  |  直到 14 年前
        1
  •  4
  •   offner    14 年前

    正如JuanManuel指出的,这是您的浏览器,保护您不受跨站点脚本攻击。如果你看一下你在小提琴手上的要求,你就能看到发生了什么。

    这是Google响应头的一部分:

    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的响应实际上已返回,但被浏览器阻止。

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

        2
  •  2
  •   juan    14 年前

    可能是因为 same origin policy

    你能试试吗 JSONP ?
    我有同样的问题(Firebug显示空数据)并用它解决了它,但是我控制了Web服务,并且可以修改它来支持它。

        3
  •  1
  •   Community paulsm4    7 年前

    两者的一个区别是 Content-Type 服务器正在报告结果:

    Fiddler显示返回的Google日历调用为 Content-Type: text/plain; charset=UTF-8 鉴于business.gov 未指定 内容类型 . application/json; charset=utf-8 (已编辑,我的初始答案来自缓存响应)。

    这个 内容类型 本质上告诉浏览器响应是什么文件类型——它相当类似于Windows中的文件扩展名。它也被称为mime类型,具有相当深远的影响(例如,它优先于html/xhtml文件中的dtd),因此如果您为xhtml提供文本/html内容类型,那么浏览器实际上会将响应视为html-- 因此,许多声称自己兼容XHTML的网站实际上提供的是无效的HTML。 .


    TheJuice 似乎在fiddler中看到了不同的结果,为了比较,这里是我在测试中看到的头:

    谷歌日历

    HTTP/1.1 200 OK
    Content-Type: text/plain; charset=UTF-8
    Expires: Tue, 22 Jun 2010 15:25:41 GMT
    Date: Tue, 22 Jun 2010 15:25:41 GMT
    Cache-Control: private, max-age=0, must-revalidate, no-transform
    Vary: Accept, X-GData-Authorization, GData-Version
    GData-Version: 1.0
    Last-Modified: Tue, 22 Jun 2010 12:19:15 GMT
    X-Content-Type-Options: nosniff
    X-Frame-Options: SAMEORIGIN
    X-XSS-Protection: 1; mode=block
    Server: GSE
    Content-Length: 49803
    

    Business.gov:

    HTTP/1.1 200 OK
    Date: Tue, 22 Jun 2010 15:34:33 GMT
    Server: Mongrel 1.1.4
    Status: 200 OK
    X-Runtime: 0.37833
    ETag: "172ec84fa79f748265e96d467af3d3dd"
    Cache-Control: private, max-age=0, must-revalidate
    Content-Type: application/json; charset=utf-8
    Content-Length: 229427
    Via: 1.1 api.business.gov
    Keep-Alive: timeout=15, max=100
    Connection: Keep-Alive