在使用Backgrid.js和Backbone-pageable的分页函数时,我在请求中推送自定义标头时遇到了问题。
初始请求正在使用xhr.setRequestHeader设置自定义标头正确获取数据。
如何使来自backgrid的所有后续请求也发送自定义标头?
var MyCollection = Backbone.PageableCollection.extend({
url: "http://api.myurl.com",
// Initial pagination states
state: {
pageSize: 10,
sortKey: "updated_at",
order: 1
},
queryParams: {
firstPage: 0,
totalPages: null,
totalRecords: null,
sortKey: "sort",
q: "state:active"
},
parseState: function (resp, queryParams, state, options) {
return {totalRecords: resp.responseData.total_count};
},
parseRecords: function (resp, options) {
return resp.responseData.items;
console.log(options);
}
});
var mycollection = new MyCollection();
var grid = new Backgrid.Grid({
columns: columns,
collection: mycollection
});
// Render the grid and attach the root to your HTML document
var $datagrid = $("#paginator-example-result");
$datagrid.append(grid.render().$el);
var paginator = new Backgrid.Extension.Paginator({
collection: mycollection
});
var myCustomRequestHeader = "ABCDEFG";
// Render the paginator
$datagrid.append(paginator.render().$el);
mycollection.fetch({reset: true, beforeSend: function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader); }, type: 'POST'}); // This works as expected, the custom header is set in the first request
提前致谢!
编辑,根据John Moses的回答,这是工作片段:
var MyCollection = Backbone.PageableCollection.extend({
...
sync: function(method, model, options){
options.beforeSend = function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader);};
return Backbone.sync(method, model, options);
}
...
});
答案 0 :(得分:1)
覆盖MyCollection的同步方法:
var MyCollection = Backbone.PageableCollection.extend({
...
sync: function(method, model, options){
options.beforeSend: function(xhr){ xhr.setRequestHeader('X-Cust-Request-Header', myCustomRequestHeader);
return Backbone.sync(method, model, options);
}
...
});