2015-09-04 52 views
3

我想添加一個http請求頭到jqueryui自動完成請求。我查看了jQuery網站上的文檔,並在那裏介紹瞭解決方案以獲取Ajax請求。我認爲解決方案在我的情況下是類似的,但我不能讓這件事情起作用。如何將標題添加到jqueryui自動完成調用?

這是我的代碼。它包裹在一個angularjs中,但是在「link」方法中的調用不會在指令內部。

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: '&' 
     } 
    }); 
}); 

我從另一篇帖子中瞭解到Stake Overflow。

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

我希望這可以幫助別人!

增強注意!我從指令中刪除了這個添加的代碼,並將其放在主應用程序模塊中,所以任何ajax調用都會將Authorization頭添加到它。很棒!