Jquery AJAX设置(发送前不工作

Jquery AJAX设置(发送前不工作,jquery,ajax,header,Jquery,Ajax,Header,登录到远程aPI服务器并获得access_令牌后,我尝试为所有后续ajax调用设置授权标头: .done(function (result) { console.log("GOT AUTHORIZATION"); amplify.store( "tokens", { access_token: result.access_token, refresh_token: result.refresh_token, token_type: result.t

登录到远程aPI服务器并获得access_令牌后,我尝试为所有后续ajax调用设置授权标头:

      .done(function (result) {
         console.log("GOT AUTHORIZATION");
         amplify.store( "tokens", { access_token: result.access_token, refresh_token: result.refresh_token, token_type: result.token_type, expires_in: result.expires_in });
         var authorization = 'Bearer ' + amplify.store( "tokens" ).access_token;
         console.log(authorization);

         $.ajaxSetup({
             beforeSend: function(xhr) {
                 xhr.setRequestHeader('Authorization', authorization);
             }
         });
在控制台上,我可以看到:

GOT AUTHORIZATION login.js:34
Bearer 6b7578772fbb4178793100651f2234de840237fe
但是后续的ajax调用都没有得到正确的头集:

https://macmini.local:8000/Categories?_=1381758170726 
无法成功,因为在标头(服务器控制台..)中找不到访问令牌

我试图修改ajax调用中的标题,但没有成功

更新的答案 从jQuery 1.5开始,
.ajax
支持
标题
属性

注意:
authorization
变量应设置在此调用之前的某个位置


旧答案
要使
ajaxSetup
工作,您需要在文档中调用它。就绪。

我知道这是一个老问题,但我从谷歌来到这里,认为其他搜索相同内容的人应该有一个工作解决方案。我尝试了建议的答案,但它对我不起作用

解决我的问题的一个解决方案是直接在
xhr
对象中设置标题:

您应该在
文档中调用它。为
ajaxSend
工作准备好了


这一点对我很有帮助。

谢谢……它是这样工作的……我还发现了如何使beforeSend在ajax调用块中工作……我忘了添加:async:false..$.ajax(“”,{type:GET“,cache:false,async:false,数据类型:“json”,beforeSend:function(xhr,settings){xhr.setRequestHeader('Authorization','Bearer'+amplify.store(“tokens”).access_token);})这可能已经过时了,现在您可以直接在$.ajax()@monothreed updated answer中设置“headers”属性,谢谢您向我指出这一点。如果没有您,我不会注意到这一点。
{ code: 400,
   error: 'invalid_request',
   error_description: 'The access token was not found',stack: undefined }
saveAccessToken: 6b7578772fbb4178793100651f2234de840237fe, client_id: 1234567890, user_id: 1
$.ajax({
    url: "http://fiddle.jshell.net/favicon.png",
    headers: {
        'Authorization': authorization
    }
})
.done(function( data ) {
    if ( console && console.log ) {
        console.log( "Sample of data:", data.slice( 0, 100 ) );
    }
});
$(function(){
    $.ajaxSetup({
        beforeSend: function(xhr) {
                 xhr.setRequestHeader('Authorization', authorization);
             }
    });
});
$(document).ajaxSend(function(ev, xhr, settings) {
  xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem(AUTH_TOKEN)}`);
  xhr.setRequestHeader('X-Marketplace', localStorage.getItem('marketplace'));
});