问题描述
有人知道如何使用 JavaScript 或 jQuery 添加或创建自定义 HTTP 标头吗?
Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?
推荐答案
根据您的需要,有多种解决方案...
There are several solutions depending on what you need...
如果您想向单个请求添加自定义标头(或标头集),则只需添加 headers
属性:
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' }
});
如果您想为每个请求添加一个默认标头(或一组标头),请使用 $.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' } });
如果您想向每个请求添加一个标头(或一组标头),那么使用 beforeSend
钩子和 $.ajaxSetup()
:
If you want to add a header (or set of headers) to every request then use the beforeSend
hook with $.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' } });
编辑(更多信息):需要注意的一件事是,使用 ajaxSetup
您只能定义一组默认标头,并且只能定义一个 beforeSend
.如果多次调用 ajaxSetup
,则只会发送最后一组标头,并且只会执行最后一个发送前回调.
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.
这篇关于如何使用 js 或 jQuery 向 ajax 请求添加自定义 HTTP 标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!