【问题标题】:Getting JSON from the Reddit Search API从 Reddit 搜索 API 获取 JSON
【发布时间】:2013-12-03 05:26:37
【问题描述】:

我正在尝试为基于 URL 的搜索加载一些 Reddit 数据,并且在 submit.json 的第 1 行上不断收到错误 Uncaught SyntaxError: Unexpected token :。我在检查器中打开了 submit.json 并检查了 - JSON 是有效的。那么,我做错了什么?我已经尝试过诸如 subreddit 搜索之类的演示,这种格式效果很好,但它似乎不适用于搜索。

function loadReddit() {
  var exampleURL = "http://www.reddit.com/submit.json?url=http://www.youtube.com/watch?v=e4dT8FJ2GE0&sort=comments";
  $.ajax({
    url: exampleURL,
    dataType: "jsonp",
    success: function(data) {
      console.log(data);
    }     
  });
}

我已经用代码发布了一个小提琴here,如果你觉得有必要,请随时编辑。

【问题讨论】:

    标签: javascript jquery jsonp reddit


    【解决方案1】:

    问题是您正在发出 JSONP 请求,但 API 为您提供了纯 JSON 响应。在 JSONP 中,响应 JSON 包装在函数调用中,并且按照惯例,函数的名称由 callback URL 参数给出。 jQuery 会为你生成这个参数,但遗憾的是 Reddit 的 API 忽略了它。

    我不得不谷歌“Reddit API JSONP”来解决这个问题,但事实证明 Reddit 期望该参数被称为 jsonp 而不是 callback。所以解决方案是使用jsonp 选项告诉jQuery 将回调名称放在jsonp 参数中:

    var resourceUrl = "http://www.reddit.com/submit.json",
        params      = { url:  "http://www.youtube.com/watch?v=e4dT8FJ2GE0",
                        sort: "comments" }
    ;
    
    $.ajax({
      url: resourceUrl,
      data:     params,   // let jQuery deal with URL parameters for you
      dataType: "jsonp",
      jsonp:    "jsonp",  // the name of the URL parameter for jQuery to give the
                          // callback function's name in    
      success: function(data) {
        console.log(data);
      }     
    });
    

    这将导致 jQuery 像这样调用 URL:

    http://www.reddit.com/submit.json
      ? jsonp = jQuery202033503812667913735_1384877326437
      & url   = http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De4dT8FJ2GE0
      & sort  = comments
      & _     = 1384877326438
    

    jsonp_ 参数是 jQuery 随机生成的。 (_ 旨在强制浏览器发出新请求,而不是先前请求的缓存结果。这是 documented 在缓存选项下,并且可以由缓存选项控制。)

    【讨论】:

    • 谢谢。很好的解决方案和解释。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2021-01-10
    • 2018-01-29
    • 1970-01-01
    • 2015-09-06
    • 2014-02-22
    • 1970-01-01
    相关资源
    最近更新 更多