我正在尝试将http请求标头添加到jqueryui自动完成请求中。我查看了jquery站点上的文档,并在那里提供了针对ajax请求的解决方案。我认为解决方案在我的情况下会是类似的,但是我无法使用这个工作。
这是我的代码。它包含在一个angularjs中,但是“link”方法中的调用将是相同的,而不会在指令中。
pthreads
答案 0 :(得分:4)
我想通了......它很棒!我不能确保它是最好的方法,但看起来非常稳固。我在autocomplete()方法之前添加了以下代码。
$.ajaxSetup({
headers: { 'Authorization': '122222222222' }
});
所以其中的新代码就像这样。
app.directive("tmBuildingSearch", function (authService) {
// I bind the $scope to the DOM behaviors.
function link(scope, element, attributes, controllers) {
//Attach the autocomplete function to the element
//NEW CODE. This attaches a custom header
$.ajaxSetup({
headers: { 'Authorization': '122222222222' }
});
element.autocomplete({
source: 'api/building/unitOrgMdl',
minLength: 2,
select: function (event, ui) {
element.val(ui.item.label);
element.blur();
scope.getbuildings({ data: ui.item })
return false;
}
});
}
// Return the directive configuration.
return ({
link: link,
restrict: "EA",
replace: true,
scope: {
getbuildings: '&'
}
});
});
我从另一篇关于Stake Overflow的帖子中得到了这个想法。
How can I add a custom HTTP header to ajax request with js or jQuery?
我希望这有助于其他人!
增强注意!我从指令中删除了这个添加的代码并将其放在主应用程序模块中,因此任何ajax调用都会将Authorization标头添加到其中。效果很棒!