在 jQuery AJAX GET 调用中传递请求标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3258645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:08:09  来源:igfitidea点击:

Pass request headers in a jQuery AJAX GET call

jqueryajaxclient-side

提问by Cranialsurge

I am trying to pass request headers in an AJAX GET using jQuery. In the following block, "data" automatically passes the values in the querystring. Is there a way to pass that data in the request header instead ?

我正在尝试使用 jQuery 在 AJAX GET 中传递请求标头。在下面的块中,“data”自动传递查询字符串中的值。有没有办法在请求标头中传递该数据?

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

The following didn't work either

以下也不起作用

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

回答by Lukas

As of jQuery 1.5, there is a headershash you can pass in as follows:

从 jQuery 1.5 开始,headers您可以传入一个哈希值,如下所示:

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

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

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

headers(added 1.5): A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

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

回答by Adam

Use beforeSend:

使用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://api.jquery.com/jQuery.ajax/

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

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

回答by enthusiast

$.ajax({
            url: URL,
            type: 'GET',
            dataType: 'json',
            headers: {
                'header1': 'value1',
                'header2': 'value2'
            },
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
               // CallBack(result);
            },
            error: function (error) {
                
            }
        });