如何使用js或jQuery向ajax请求添加自定义HTTP标头?

Txu*_*ugo 309 javascript ajax jquery httprequest http-headers

有谁知道如何使用JavaScript或jQuery添加或创建自定义HTTP标头?

Pre*_*aul 560

根据您的需要,有几种解决方案......

如果要将自定义标头(或标头集)添加到单个请求,则只需添加headers属性:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});
Run Code Online (Sandbox Code Playgroud)

如果要为每个请求添加默认标头(或标头集),请使用$.ajaxSetup():

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
Run Code Online (Sandbox Code Playgroud)

如果要为每个请求添加标头(或标头集),请 使用以下beforeSend钩子$.ajaxSetup():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
Run Code Online (Sandbox Code Playgroud)

编辑(更多信息):需要注意的一点是,ajaxSetup您只能定义一组默认标题,而您只能定义一个标题beforeSend.如果ajaxSetup多次调用,则只会发送最后一组标题,并且只会执行最后一次发送前回调.

  • 你只能定义一个`beforeSend`回调.如果你调用`$ .ajaxSetup({beforeSend:func ...})`两次,那么第二个回调将是唯一一个触发的回调. (3认同)
  • 看起来它不适用于CORS请求(每个浏览器).有工作吗? (2认同)

Szi*_*zsi 52

或者,如果要为每个将来的请求发送自定义标头,则可以使用以下内容:

$.ajaxSetup({
    headers: { "CustomHeader": "myValue" }
});
Run Code Online (Sandbox Code Playgroud)

这样,除非被请求的选项明确覆盖,否则每个未来的ajax请求都将包含自定义标头.你可以在这里找到更多信息ajaxSetup


小智 19

以下是使用XHR2的示例:

function xhrToSend(){
    // Attempt to creat the XHR2 object
    var xhr;
    try{
        xhr = new XMLHttpRequest();
    }catch (e){
        try{
            xhr = new XDomainRequest();
        } catch (e){
            try{
                xhr = new ActiveXObject('Msxml2.XMLHTTP');
            }catch (e){
                try{
                    xhr = new ActiveXObject('Microsoft.XMLHTTP');
                }catch (e){
                    statusField('\nYour browser is not' + 
                        ' compatible with XHR2');                           
                }
            }
        }
    }
    xhr.open('POST', 'startStopResume.aspx', true);
    xhr.setRequestHeader("chunk", numberOfBLObsSent + 1);
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState == 4 && xhr.status == 200) {
            receivedChunks++;
        }
    };
    xhr.send(chunk);
    numberOfBLObsSent++;
}; 
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.

如果创建对象,则可以使用setRequestHeader函数在发送请求之前指定名称和值.

  • 除非你试图在现有的XHR2调用中添加一个标题,并且不想开始重写它以便只使用jQuery ...在这一点上,@ gryzzly有唯一可行的答案. (4认同)
  • 虽然这在2011年可能是正确的,但通常不要重新发明轮子,而是使用像Zepto或jQuery这样的AJAX库. (2认同)

Jay*_*dra 19

假设JQuery ajax,您可以添加自定义标头,如 -

$.ajax({
  url: url,
  beforeSend: function(xhr) {
    xhr.setRequestHeader("custom_header", "value");
  },
  success: function(data) {
  }
});
Run Code Online (Sandbox Code Playgroud)


Rol*_* T. 17

您也可以在不使用jQuery的情况下执行此操作.覆盖XMLHttpRequest的send方法并在那里添加标题:

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
    this.setRequestHeader('x-my-custom-header', 'some value');
    this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;
Run Code Online (Sandbox Code Playgroud)


Ste*_* D. 12

您应该避免使用文档中$.ajaxSetup()描述的内容.请改用以下内容:

$(document).ajaxSend(function(event, jqXHR, ajaxOptions) {
    jqXHR.setRequestHeader('my-custom-header', 'my-value');
});
Run Code Online (Sandbox Code Playgroud)


Que*_*tin 6

假设您的意思是"当使用ajax"和"HTTP 请求标头"时,请使用headers您传递给的对象中的属性ajax()

标题(添加1.5)

默认: {}

要与请求一起发送的其他标头键/值对的映射.在调用beforeSend函数之前设置此设置; 因此,可以从beforeSend函数中覆盖标题设置中的任何值.

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