$.ajaxSetup为将来的Ajax请求设置默认值.
Its use is not recommended as suggested in the JQuery documentation.
无论如何,因为它设置了将来调用的默认值,它必须在所有依赖于这些默认值的ajax调用之前执行.例如,如果您没有提到调用的url,则$ajaxSetup中配置的默认URL将是调用的url.如果您所做的调用取决于那些默认值,那么此代码
self.authenticate = function () {
self.token = sessionStorage.getItem(tokenKey);
var headers = {};
if (self.token) {
headers.Authorization = 'Bearer ' + self.token;
$.ajaxSetup({
headers: headers
});
}
}
必须在进行以下调用之前执行.
self.getUsers = function () {
$.get("../API/Users/GetUsers/");
}
现在检查一下
*************** Plunker for answer ****************
在那个plunker中,按F12键进入开发者控制台中的网络选项卡,然后检查$.ajax()和$.get()进行的调用中的标题.
我在观察到的那个(要点读)点,
>如果调用是$.ajax(),那么标题显示,并且调用的url是$.ajaxSetup中提到的url
>如果调用是$.get(),那么标题不显示,调用的url是plunker url,意味着它将是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
有关更多信息
如果你愿意,可以测试一下.
$.ajax()调用的图片
$.get()调用的图片
因此,如果要设置标题,只需使用$.ajax()而不是$.get()
希望这可以帮助 :)