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

时间:2022-03-21 06:45:17

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

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

8 个解决方案

#1


517  

There are several solutions depending on what you need...

有几种解决方案取决于你需要什么……

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

如果您想要向单个请求添加自定义的标题(或一组标题),那么只需添加标题属性:

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

If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

如果您想在每个请求中添加一个默认的标头(或头集),那么使用$.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' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

如果您想在每个请求中添加一个头(或一组标题),那么就使用$.ajaxSetup()的bepreend挂钩():

$.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' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

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

#2


49  

Or, if you want to send the custom header for every future request, then you could use the following:

或者,如果您想要发送每个未来请求的自定义标头,那么您可以使用以下内容:

$.ajaxSetup({
    headers: { "CustomHeader": "myValue" }
});

This way every future ajax request will contain the custom header, unless explicitly overridden by the options of the request. You can find more info on ajaxSetup here

这样,每个未来的ajax请求都将包含自定义头,除非被请求的选项显式覆盖。你可以在这里找到更多关于ajaxSetup的信息。

#3


16  

Assuming JQuery ajax, you can add custom headers like -

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

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

#4


16  

Here's an example using XHR2:

这里有一个使用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++;
}; 

Hope that helps.

希望有帮助。

If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.

如果创建对象,则可以使用setRequestHeader函数来分配一个名称,并在发送请求之前指定一个值。

#5


13  

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

您也可以在不使用jQuery的情况下做到这一点。重写XMLHttpRequest的发送方法并在那里添加标题:

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;

#6


9  

You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

您应该避免使用文档中描述的$. ajaxsetup()。使用以下:

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

#7


6  

Assuming that you mean "When using ajax" and "An HTTP Request header", then use the headers property in the object you pass to ajax()

假设您的意思是“使用ajax”和“HTTP请求头”,那么在传递给ajax的对象中使用header属性()

headers(added 1.5)

头(1.5)

Default: {}

默认值:{ }

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.

要发送请求的附加头键/值对的映射。该设置是在调用前的函数之前设置的;因此,头部设置中的任何值都可以从该函数中重写。

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

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

#8


3  

"setRequestHeader" method of XMLHttpRequest object should be used

应该使用XMLHttpRequest对象的“setRequestHeader”方法。

http://help.dottoro.com/ljhcrlbv.php

http://help.dottoro.com/ljhcrlbv.php

#1


517  

There are several solutions depending on what you need...

有几种解决方案取决于你需要什么……

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

如果您想要向单个请求添加自定义的标题(或一组标题),那么只需添加标题属性:

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

If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

如果您想在每个请求中添加一个默认的标头(或头集),那么使用$.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' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

如果您想在每个请求中添加一个头(或一组标题),那么就使用$.ajaxSetup()的bepreend挂钩():

$.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' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

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

#2


49  

Or, if you want to send the custom header for every future request, then you could use the following:

或者,如果您想要发送每个未来请求的自定义标头,那么您可以使用以下内容:

$.ajaxSetup({
    headers: { "CustomHeader": "myValue" }
});

This way every future ajax request will contain the custom header, unless explicitly overridden by the options of the request. You can find more info on ajaxSetup here

这样,每个未来的ajax请求都将包含自定义头,除非被请求的选项显式覆盖。你可以在这里找到更多关于ajaxSetup的信息。

#3


16  

Assuming JQuery ajax, you can add custom headers like -

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

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

#4


16  

Here's an example using XHR2:

这里有一个使用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++;
}; 

Hope that helps.

希望有帮助。

If you create your object, you can use the setRequestHeader function to assign a name, and a value before you send the request.

如果创建对象,则可以使用setRequestHeader函数来分配一个名称,并在发送请求之前指定一个值。

#5


13  

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

您也可以在不使用jQuery的情况下做到这一点。重写XMLHttpRequest的发送方法并在那里添加标题:

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;

#6


9  

You should avoid the usage of $.ajaxSetup() as described in the docs. Use the following instead:

您应该避免使用文档中描述的$. ajaxsetup()。使用以下:

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

#7


6  

Assuming that you mean "When using ajax" and "An HTTP Request header", then use the headers property in the object you pass to ajax()

假设您的意思是“使用ajax”和“HTTP请求头”,那么在传递给ajax的对象中使用header属性()

headers(added 1.5)

头(1.5)

Default: {}

默认值:{ }

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.

要发送请求的附加头键/值对的映射。该设置是在调用前的函数之前设置的;因此,头部设置中的任何值都可以从该函数中重写。

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

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

#8


3  

"setRequestHeader" method of XMLHttpRequest object should be used

应该使用XMLHttpRequest对象的“setRequestHeader”方法。

http://help.dottoro.com/ljhcrlbv.php

http://help.dottoro.com/ljhcrlbv.php