2013-01-05 13 views
6

我正在使用github API进行小型网络应用程序,并且在某些时候我需要获得link headerthe paginationGithub API使用ajax获取链接标题

最终的目标是让每个仓库的更新总数,我发现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分别是用户的名字和他的名字回购

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

回答

5

见GitHub的API文档使用JSONP回调:http://developer.github.com/v3/#json-p-callbacks

基本上,如果你正在使用JSONP调用API,那么你不会得到一个Link头,但是你反而会得到相同的信息在响应JSON文件(即正文)中。下面是从API文档的示例中,注意到Link属性在meta对象

$ 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 
    } 
}) 
+0

这是完美的,谢谢 –

0

用于将传递给getJSON方法的功能的签名是 类型:Function(PlainObject数据,字符串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 
    });