且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-07-21 07:49:54

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

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.