XMLHttpRequest对象提供了一个设置请求头的方法:setRequestHeader,对应的jQuery可以再beforeSend回调里面设置请求头:
$.ajax({
type: "GET",
url: "test.php",
success: function(data) {
console.log(data);
},
beforeSend: function(xhr) {
token = window.localStorage.getItem('token');
xhr.setRequestHeader("Authorization", "Basic " + btoa(token + ":"));
}
});