I need to read response headers in an Ajax request made by backbone.js fetch method. is there any way to read headers if I override the fetch method:
var PageCollection = Backbone.Collection.extend({
url: 'http://localhost/cms?_mn=Mod_Admin&_mf=getAllPages',
model: PageModel,
fetch: function (options) {
Backbone.Collection.prototype.fetch.call(this, options);
// The above line of code works and fetch the dataset
// BUT how i can read the response headers at this point
}
});
I need to read response headers in an Ajax request made by backbone.js fetch method. is there any way to read headers if I override the fetch method:
var PageCollection = Backbone.Collection.extend({
url: 'http://localhost/cms?_mn=Mod_Admin&_mf=getAllPages',
model: PageModel,
fetch: function (options) {
Backbone.Collection.prototype.fetch.call(this, options);
// The above line of code works and fetch the dataset
// BUT how i can read the response headers at this point
}
});
Share
Improve this question
asked Dec 6, 2013 at 13:46
asim-ishaqasim-ishaq
2,2206 gold badges33 silver badges57 bronze badges
4 Answers
Reset to default 16Use "success" callback to get the xhr object, so you will have an ability to get all the response headers:
collection.fetch({
success: function (collection, response, options) {
options.xhr.getAllResponseHeaders(); // To get all the headers
options.xhr.getResponseHeader('header_name'); // To get just one needed header
}
});
The Backbone fetch()
method returns a jqXHR
object. You can call done()
on this object to add a callback that will be invoked when the request is complete. Then use the getResponseHeader()
method on the same jqXHR
object to get the value of the header that you're interested in, or call getAllResponseHeaders()
to get all headers.
So in your override of the fetch()
method you can do something like this:
var jqXHR = Backbone.Collection.prototype.fetch.call(this, options);
jqXHR.done(function() {
// Get all headers:
console.log('All headers:', jqXHR.getAllResponseHeaders());
// Or get a specific header:
console.log('Content-Length:', jqXHR.getResponseHeader('Content-Length'));
});
take look at my implementation and how I used parse function
var CustomPageCollection = Backbone.Collection.extend({
model: CustomPage,
url: '/pb/editor/pages',
parse: function(resp, xhr) {
this.paginationInfo = JSON.parse(xhr.getResponseHeader('X-Pagination-Info'));
return resp.items;
}
});
i found out a nicer way: the collection fires a "parse" function, when coming back from the server BakcboneJs - collection Parse
parse:function(a,b,c){
console.log("a",a);
console.log("b",b);
console.log("c",c);
},
our buddy is at b :)