【问题标题】:Github API get the link header with ajaxGithub API 使用 ajax 获取链接头
【发布时间】:2013-01-05 06:27:53
【问题描述】:

我将 github api 用于小型 Web 应用程序,有时我需要为 the pagination 获取 link header

最终目标是获取每个存储库的提交总数,我发现python script 并尝试将其调整为 JavaScript。

getData = $.getJSON('https://api.github.com/repos/'+user+'/'+repo+'/commits?callback=?', function (commits){

    console.log(getData.getResponseHeader('link'))
    // will return null

    console.log(getData.getAllResponseHeaders('link'))
    // will return an empty string

    console.log(commits)
    // will successfuly return my json
});

userrepo分别是用户名和他的repo名

这是一个 Github 页面,所以我只能使用 JavaScript。

【问题讨论】:

    标签: javascript jquery http-headers github-api


    【解决方案1】:

    有关使用 JSONP 回调的信息,请参阅 GitHub API 文档:http://developer.github.com/v3/#json-p-callbacks

    基本上,如果您使用 JSONP 调用 API,那么您将不会获得 Link 标头,但您会在响应 JSON 文档(即正文)中获得相同的信息。以下是 API 文档中的示例,请注意 meta 对象中的 Link 属性

    $ curl https://api.github.com?callback=foo
    
    foo({
      "meta": {
        "status": 200,
        "X-RateLimit-Limit": "5000",
        "X-RateLimit-Remaining": "4966",
        "Link": [ // pagination headers and other links
          ["https://api.github.com?page=2", {"rel": "next"}]
        ]
      },
      "data": {
        // the data
      }
    })
    

    【讨论】:

      【解决方案2】:

      您传递给getJSON 方法的函数的签名是 类型:函数(PlainObject data, String textStatus, jqXHR jqXHR)

      要访问链接头,您应该使用 jqXHR 对象而不是数据对象:

      getData = $.getJSON(
           'https://api.github.com/repos/'+user+'/'+repo+'/commits?callback=?',
           function (data, textStatus, jqXHR){
      
              console.log(jqXHR.getResponseHeader('Link'))
              // will return the Header Link
      
              console.log(commits)
              // will successfuly return my json
          });
      

      【讨论】:

        猜你喜欢
        • 2012-02-02
        • 1970-01-01
        • 1970-01-01
        • 2013-09-24
        • 2022-01-24
        • 1970-01-01
        • 1970-01-01
        • 2017-02-02
        • 1970-01-01
        相关资源
        最近更新 更多