我试图在AJAX GET中使用jQuery传递请求头。在下面的块中,"data"自动传递查询字符串中的值。是否有一种方法可以在请求头中传递该数据?

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         success: function() { alert('Success!' + authHeader); }
      });

下面的方法也不管用

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         beforeSend: { signature: authHeader },
         async: false,                    
         type: "GET",
                    success: function() { alert('Success!' + authHeader); }
      });

当前回答

使用beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

其他回答

使用beforeSend:

$.ajax({
         url: "http://localhost/PlatformPortal/Buyers/Account/SignIn",
         data: { signature: authHeader },
         type: "GET",
         beforeSend: function(xhr){xhr.setRequestHeader('X-Test-Header', 'test-value');},
         success: function() { alert('Success!' + authHeader); }
      });

http://api.jquery.com/jQuery.ajax/

http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method

从jQuery 1.5开始,你可以像下面这样传入一个头部散列:

$.ajax({
    url: "/test",
    headers: {"X-Test-Header": "test-value"}
});

从http://api.jquery.com/jQuery.ajax:

headers(1.5新增):附加头键/值对的映射,随请求一起发送。该设置是在调用beforeSend函数之前设置的;因此,在报头设置中的任何值都可以在beforeSend函数中被覆盖。

. ajax({美元 url: url、 类型:“得到”, 数据类型:json, 标题:{ “header1”:“value1”, “header2”:“value2” }, contentType:“application / json;charset = utf - 8 ', 成功:函数(结果){ / /回调(结果); }, 错误:函数(错误){ } });