jquery - 如何从 facebook 页面墙获取 json 或 jsonp 而不会在 Chrome 中出现 mime 错误

标签 jquery ajax facebook jsonp

我看过诸如this one之类的帖子这表明您可以获取公共(public) Facebook 页面的 JSON 墙。 但他们没有给出有效的例子。我尝试使用 $.ajaxjsonp 获取它,但在 Chrome 中出现 mime 错误,在 Safari 中出现不同的错误,在 FireFox 中出现另一个不同的错误。我错过了什么?

我创建了一个 jsFiddle HERE记录控制台,代码如下

 $.ajax({
      url: 'https://www.facebook.com/feeds/page.php?id=54971236771&format=JSON',
      type: 'get',
      dataType: 'jsonp',
      error: function (jqXHR, textStatus, errorThrown) {
           console.log('Problem with call to get list of articles\n',errorThrown);
      },
      success: function (data) {
           console.log('call success, data is\n', data);
      }
 });

最佳答案

当前浏览器禁止跨域 JSON 请求。 JSON 请求如下所示:

{ foo: 'bar' }

您获得的文件是纯 JSON,在当前所有浏览器中都是禁止的。 但 JSONP 是允许的。 JSONP 看起来像:

mycallback({ foo: 'bar' });

当您的网址类似于 https://www.facebook.com/feeds/page.php?id=54971236771&format=JSON 时,结果就是 JSON。

要获取 JSONP,您需要使用 facebook API url,并且需要从 facebook 获取特殊的 facebook API token :

https://graph.facebook.com/54971236771/feed?access_token=YOUR-TOKEN-GOES-HERE

实际的 URL 将是这样的:

https://graph.facebook.com/54971236771/feed?access_token=YOUR-TOKEN-GOES-HERE&callback=jQuery110208932981239631772_1401824402598&_=1401824402599

完整代码如下:

$.ajax({
    url: 'https://graph.facebook.com/54971236771/feed?access_token=YOUR-TOKEN-GOES-HERE',
    type: 'get',
    dataType: 'jsonp',
    error: function (jqXHR, textStatus, errorThrown) {
        console.log('Problem with call to get list of articles\n', errorThrown);
    },
    success: function (data) {
        console.log('call success, data is\n', data);
    }
});

关于jquery - 如何从 facebook 页面墙获取 json 或 jsonp 而不会在 Chrome 中出现 mime 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24022795/

相关文章:

javascript - JQuery .toggleClass() 一次有两个类?

javascript - 更改 Flipswitch jquery mobile 的事件状态

javascript - PHP Ajax onkeyup 在我的 Switch 案例网站上不起作用

javascript - 使用XMLHttpRequest加载多个音频文件并将其附加以在Web Audio API中播放

facebook - 如何获得邀请 friend 的用户?

javascript - Conceal Div 内的社交媒体按钮

ajax - "Redirect"页面没有刷新(Facebook 照片样式)

javascript - 滚动偏移和元素的两个条件

jquery - 取消绑定(bind)一组 img 上的悬停事件

javascript - 在同级自执行函数中调用函数