Jonathan de M. Jonathan de M. -4 years ago 134
Javascript Question

Github API get the link header with ajax

I'm using github api for a small web app and at some point I need to get link header for the pagination.

The final goal is to get the total number of commits per repository, I found that python script and tried to adapt it to 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
});


user
and
repo
are respectively the user name and his repo name

It's for a Github page so I can only use JavaScript.

Answer Source

See the GitHub API docs for using JSONP callbacks: http://developer.github.com/v3/#json-p-callbacks

Basically, if you're using JSONP to call the API, then you won't get a Link header, but you will instead get the same information in the response JSON document (i.e. the body). Below is the example from the API docs, notice the Link property in the meta object

$ 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
  }
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download