0
在使用Backgrid.js和Backbone-pageable使用分頁函數時,我在請求中推送自定義頭時遇到問題。Backgrid/Backbone Pageable:使用GET請求的自定義HTTP頭
初始請求正在使用xhr.setRequestHeader設置自定義標頭正確獲取數據。
如何使所有後續的請求從發送自定義頭文件?
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
在此先感謝!
編輯,基於以下約翰·摩西的答案,這是工作片段:
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);
}
...
});
真棒,非常感謝。 – Monty
@Monty請不要將您的解決方案添加到答案中,將它添加到您的問題。 –