2015-09-04 2 views
3

Я пытаюсь добавить http-заголовок запроса в запрос автозаполнения jqueryui. Я просмотрел документацию на сайте jquery, и решение представлено там для запросов ajax. Я предположил, что решение будет похоже в моем случае, но я не могу заставить эту работу работать.Как добавить заголовки в автозаполнение jqueryui?

Вот мой код. Он завернут в угловой указатель, но вызов внутри метода «ссылка» будет таким же, если он не находится внутри директивы.

app.directive("buildingSearch", function() { 
    // I bind the $scope to the DOM behaviors. 
    function link(scope, element, attributes, controllers) { 
     //Attach the autocomplete functionto the element 
     element.autocomplete({ 
      source: 'api/building/unitOrgMdl', 
      minLength: 2, 

      //********* 
      //This is the addition I made as per the jquery documentation that I figured would work but doesn't 
      headers: { 
       'Authorization': '122222222222' 
      }, 
      //********* 

      select: function (event, ui) { 
       element.val(ui.item.label); 
       element.blur(); 
       scope.getbuildings({ data: ui.item }) 
       return false; 
      } 
     }); 
    } 

    // Return the directive confirugation. 
    return ({ 
     link: link, 
     restrict: "EA", 
     replace: true, 
     scope: { 
      getbuildings: '&' 
     } 
    }); 
}); 

ответ

3

Я понял, и он отлично работает! Я не могу гарантировать, что это лучший способ сделать это, но кажется довольно солидным. Я добавил следующий код непосредственно перед методом 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: '&' 
     } 
    }); 
}); 

У меня появилась идея из другого сообщения о переполнении коллажа.

How can I add a custom HTTP header to ajax request with js or jQuery?

Я надеюсь, что это помогает кто-то другой!

УЛУЧШЕНИЕ ЗАМЕЧАНИЯ! Я удалил этот добавленный код из директивы и поместил его в основной модуль приложения, поэтому ЛЮБОЙ вызов ajax получит заголовок авторизации, добавленный к нему. Прекрасно работает!

Смежные вопросы