我有以下函数来设置我的 AJAX
请求的 header :
self.authenticate = function () {
self.token = sessionStorage.getItem(tokenKey);
var headers = {};
if (self.token) {
headers.Authorization = 'Bearer ' + self.token;
$.ajaxSetup({
headers: headers
});
}
}
但这不起作用,当我检查开发者收费 (F12) 或 Fiddler 中的 header 时,我在那里看不到自定义 header ,但是当我在请求上设置 header 而不是通过 ajaxSetup
完美运行。
authenticate
函数正在布局页面中调用:
$(document).ready(function () {
var avm = new AuthenticationViewModel();
avm.authenticate();
});
并且self.token
不是null
。
例如,对于这个请求:
self.getUsers = function (callback) {
$.get("../API/Users/GetUsers/",callback);
}
我错过了什么?
最佳答案
$.ajaxSetup为 future 的 Ajax 请求设置默认值。
Its use is not recommended as suggested in the JQuery documentation.
无论如何,因为它为将来的调用设置了默认值,所以它必须在依赖于这些默认值的所有 ajax 调用之前执行。例如,如果您没有提及调用的 url
,则在 $ajaxSetup
中配置的默认 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 转到 developer console 中的 network 选项卡,并检查 调用的 header $.ajax()
和 $.get()
在 plunker 中我观察到(要阅读的要点),
- 如果调用是
$.ajax()
则显示 header 并且调用的url
是url
在$.ajaxSetup
中提到的
- 如果调用是
$.get()
,则 header 不会显示,调用的url
是plunker
url 意味着在你的情况下它将是http://MySite/
等等。
$.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
获取更多信息
DIFFERENCE BETWEEN $.ajax() and $.get(), $.post()
如果需要,只需测试 plunker。
$.ajax() 调用的图片
$.get() 调用的图片
因此,如果你想设置 headers
只需使用 $.ajax()
而不是 $.get()
希望这有帮助:)
关于javascript - $.ajaxSetup 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493494/