$.ajaxSetup sets default values for future Ajax requests.
Its use is not recommended as suggested in the JQuery documentation.
Anyways, as it sets the default values for future calls it must execute before all ajax calls that depends on those default values. For example, if you didn't mention the url
of the call, the default url
that configured in the $ajaxSetup
will be the url
of the call. If the call you made depends on those defaults then this code
self.authenticate = function () {
self.token = sessionStorage.getItem(tokenKey);
var headers = {};
if (self.token) {
headers.Authorization = 'Bearer ' + self.token;
$.ajaxSetup({
headers: headers
});
}
}
must execute before the below call is made.
self.getUsers = function () {
$.get("../API/Users/GetUsers/");
}
Now check this
***************Plunker for answer****************
In that plunker go to network tab in the developer console by pressing F12 and check the headers in those calls made by $.ajax()
and $.get()
In the plunker I observed that(Points to be read),
- If the call is
$.ajax()
then the headers are showing and the url
of the call is the url
that is mentioned in the $.ajaxSetup
- If the call is
$.get()
then the headers are not showing and the url
of the call is the plunker
url means in your case it will be http://MySite/
etc.
$.ajax()
is the most configurable one, where you get fine grained
control over HTTP headers and such. You're also able to get direct
access to the XHR-object using this method. Slightly more fine-grained
error-handling is also provided. Can therefore be more complicated and
often unecessary, but sometimes very useful. You have to deal with the
returned data yourself with a callback.
$.get()
is just a shorthand for $.ajax()
but abstracts some of the
configurations away, setting reasonable default values for what it
hides from you. Returns the data to a callback. It only allows
GET-requests so is accompanied by the $.post()
function for similar
abstraction, only for POST
For more info
DIFFERENCE BETWEEN $.ajax() and $.get(), $.post()
Just test the plunker if you want.
Image of $.ajax() call

Image of $.get() call

Hence, If you want to set the headers
just use $.ajax()
instead of $.get()
Hope this helps :)