您可以将令牌存储在本地存储器或cookies中,这两种方法都可以。然后,当您进行ajax调用时,您将从使用的值中检索该值,并将其添加到传出的ajax请求中。具体如何实现这一点将取决于您使用的具体ajax实现。例如,google“AddAuthTokentojQuery.ajax”,您将找到该库的正确语法
像这样的方法会奏效:
// do initial login and get token
var token = response.access_token;
// store it in local storage
localStorage.setItem('apiKey', token);
// ... navigate around and what not...
// later, when you need to make another call, get the token
var token = localStorage.getItem('apiKey');
$.ajax({
url: url,
method: "POST",
dataType: "json",
//.. other props as needed...
beforeSend: function (xhr) {
/* set the Authorization header with the token */
xhr.setRequestHeader("Authorization", "Bearer " + token);
},
success: function (data) {
// do something cool with data
},
error: function (jqXHR, textStatus, errorThrown) {
// handle errors ...
}
});