在Select2上将自定义标头传递给Ajax请求
我们正在尝试在Select2中实现Ajax远程数据加载: –
$scope.configPartSelect2 = { minimumInputLength: 3, ajax: { url: "/api/Part", // beforeSend: function (xhr) { xhr.setRequestHeader('Authorization-Token', http.defaults.headers.common['Authorization-Token']); }, // headers: {'Authorization-Token': http.defaults.headers.common['Authorization-Token']}, data: function (term, page) { return {isStockable: true}; }, results: function (data, page) { // parse the results into the format expected by Select2. // since we are using custom formatting functions we do not need to alter remote JSON data return { results: data }; } } };
我们正在使用AngularJS。 对于每个Http请求,我们将其默认设置为将Authtoken作为标头。 但不知何故,它不能与Select2 Ajax请求一起使用。 在上面的代码中,注释代码是我失败的尝试。
摘自select2的演示页面:
Select2会将ajax对象中的任何选项传递给jQuery的$ .ajax函数或您指定的传输函数。
使用JQuery 2+,我能够成功设置OAuth 2.0和Content-Type标头。
ajax: { headers: { "Authorization" : "Bearer "+Cookies.get('accessToken'), "Content-Type" : "application/json", }, }
这就是我修复发送身份validation令牌的方法。 只需将其添加为Select2 ajax param;
transport: function(params){ params.beforeSend = function(request){ request.setRequestHeader("Authorization", 'OAuth ' + api_access_token); }; return $.ajax(params); },
另外一个选项:
ajax: { url: '/api/Part', params: { headers: { "Authorization": "XXX" } }, ... }
我通过提供自定义传输方法解决了我的上述问题。然后我被困在Drop-down项目没有被选中鼠标hover和下拉项目没有被选中后点击。 调试后我发现proeprty“id”必须在返回的json对象中。
以下是我的代码: –
var fetchPart = function (queryParams) { var result = http.get(queryParams.url, queryParams.data).success(queryParams.success); result.abort = function() { return null; }; return result; }; var partFormatResult = function (part) { return "" + part.PartNumber + "
"+ part.PartDescription + "
"; }; var partFormatSelection = function (part, container) { console.log(part.Id + "number - " + part.PartNumber); return part.PartNumber; // return part.PartNumber; //return part.Id; }; $scope.configPartSelect2 = { minimumInputLength: 3, ajax: { url: "/api/Part", data: function (term, page) { return { params: { isStockable: true, query: term, pageNo: page } }; }, transport: fetchPart, results: function (data, page) { console.log("result is called by select2"); var more = (page * 10) <= data.length; // whether or not there are more results available return { results: data, more: more }; } }, formatResult: partFormatResult, formatSelection: partFormatSelection, dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller };
你可以这样做:
transport: function (params, success, failure) { params.beforeSend = function (request) { request.setRequestHeader("Authorization-Token", http.defaults.headers.common['Authorization-Token']); }; var $request = $.ajax(params); $request.then(success); $request.fail(failure); return $request; }