且构网

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

向所有 jQuery AJAX 请求添加自定义 http 标头

更新时间:2022-01-31 07:26:48

预过滤器是实现此目的的简单方法:

A pre-filter would be an easy way of accomplishing this:

$.ajaxPrefilter(function( options ) {
    if ( !options.beforeSend) {
        options.beforeSend = function (xhr) { 
            xhr.setRequestHeader('CUSTOM-HEADER-KEY', 'CUSTOM-HEADER-VALUE');
        }
    }
});

这样所有请求都将获得自定义标头,除非特定请求覆盖了 beforeSend 选项.

this way all requests will get the custom header, unless the specific request overrides the beforeSend option.

但是请注意,您可以使用 ajaxSetup 实现相同的目标.存在警告的唯一原因是因为使用它会影响所有 ajax 请求(就像我的方法一样),如果特定请求不需要该选项集,可能会导致不需要的结果.我建议只使用 ajaxSetup,毕竟这就是它的用途.

Note however you can accomplish the same goal using ajaxSetup. the only reason that warning is there is because using it will affect all ajax requests (just like my method will), possibly resulting in unwanted results if a specific request didn't need that option set. I'd suggest just using ajaxSetup, that is what it's there for after all.