【问题标题】:$.getJSON get silent error on retrieving data$.getJSON 在检索数据时出现静默错误
【发布时间】:2011-04-14 20:35:40
【问题描述】:

我尝试从 JSon 服务中检索数据,但我遇到了一些问题,无法通过调试过程。

我从这个动态服务中检索数据:http://www.synergiescanada.org/json/otherpublicationbyid?synid=synergies:bcn.arbutus.215.3263 我用这个工具验证了结果http://jsonformatter.curiousconcept.com/,它看起来很好。

[
   {
      "name":"Dr. Andre Smith",
      "publications":[
         {
            "id":"synergies:bcn.arbutus.215.3264",
            "title":"Exploring death and dying through discourse",
            "uri":"http:\/\/journals.uvic.ca\/index.php\/arbutus\/article\/view\/3264",
            "date":"2010-10-18"
         }
      ]
   }
]

但是以另一种方式,当我使用 jquery 中的 .getJSON 方法时,它会失败。

<script type="text/javascript"> 
$(document).ready(function() {
  $.getJSON("http://www.synergiescanada.org/json/otherpublicationbyid?synid=synergies:bcn.arbutus.215.3263" , 
    function(json) {
    alert(json);
  });
</script> 

永远不会触发弹出警报,据我所知,getJSON 在检索我的 JSON 数据时遇到一些错误后会默默地失败。

我尝试使用 firebug 进行调试,我刚刚在控制台中发现了这个关于标题的信息

(对不起,我可以添加图片我是新人)

Response Headersview source
Date    Thu, 14 Apr 2011 20:24:49 GMT
X-Powered-By    PHP/5.3.5
Cache-Control   store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Disposition inline; filename=author.json
Last-Modified   Thu, 14 Apr 2011 20:24:49 GMT
Content-Type    application/json
Set-Cookie  SESS65d098c5115a6dff636c637d3c170001=c82ctlcfe0926dr45jrge1crf5; expires=Sat, 07-May-2011 23:58:09 GMT; path=/; domain=www.synergiescanada.org
Expires Sun, 19 Nov 1978 05:00:00 GMT
Connection  keep-alive, timeout=50, maxreq=60
Transfer-Encoding   chunked

Request Headersview source
Host    www.synergiescanada.org
User-Agent  Mozilla/5.0 (X11; U; Linux x86_64; en-CA; rv:1.9.2.16) Gecko/20110323 Ubuntu/10.10 (maverick) Firefox/3.6.16
Accept  application/json, text/javascript, */*; q=0.01
Accept-Language fr-ca,fr;q=0.8,en-ca;q=0.6,en-us;q=0.4,en;q=0.2
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  115
Connection  keep-alive
Referer http://localhost/test/ajax.html
Origin  http://localhost

同一个演示页面从 flickr 触发 JSON api,它根本没有抱怨,所以看起来我在这里错过了一些东西。也许很明显。

如果有人能给我一个线索,我将不胜感激。

【问题讨论】:

  • Ajax 不允许跨域请求,因此您的 getJSON 调用失败,因为您正在从从本地主机加载的页面向synergiescanada.org 发出调用,这是两个不同的域。
  • 另外,您的 json 变量将是一个对象,而不是一个字符串。您需要使用 alert(json.name);alert(json.publications[0].title);
  • 感谢目标是触发警报。即使带有“对象”标签,它也应该意味着请求成功。

标签: javascript jquery json


【解决方案1】:

看起来像一个跨站点脚本问题——您试图从外部站点的本地主机获取数据。一种解决方法是使用 PHP 作为“代理”。见:http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html

【讨论】:

  • 感谢 Gary 和 Cyber​​nate。我认为 json 请求可能是跨域的,与 Ajax 请求不同。正如我所说,我使用来自 Jquery 网站的示例代码从 flickr 检索图像,并且我没有使用这个本地页面进入 flickr 域(我使用相同的调用)。所以它可以工作,但不适用于我构建的协同效应中的 JSON,我试图找出原因。
  • 我最终通过停止使用跨站点脚本解决了这个问题。我使用 Ajax 查询来请求 JSON。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 2020-05-18
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
相关资源
最近更新 更多