将自定义http标头添加到所有jQuery AJAX请求中

问题描述:

澄清点:我在向jQuery ajax调用添加自定义标头时没有任何问题,我希望自动将自定义标头添加到所有ajax调用中。

Point of clarification: I don't have any problem adding a custom header to my jQuery ajax call, I want to have my custom header added to all ajax calls automatically.

如果你看一下 jquery $ .ajax自定义http标题问题(不是我的问题),如果每次ajax调用手动实现,你会看到代码如何工作的一个很好的例子。

If you take a look at jquery $.ajax custom http headers issue (not my question), you'll see a pretty good example of how the code works if implemented by hand for each ajax call.

我想覆盖beforeSend用于所有jQuery ajax调用。根据jQuery文档,我可以使用 jQuery.ajaxSetup()来做到这一点,但那里是一个警告说你可能不应该,可能会导致意外行为,所有这些。对于这种全球回调,他们建议使用.ajaxStart()。 .ajaxStart()看起来很棒,除了它没有公开XHR所以我可以添加标题。

I'd like to override beforeSend for all jQuery ajax calls. According to the jQuery documentation I can do this by using jQuery.ajaxSetup(), but there is a warning saying you probably shouldn't, may cause unexpected behavior, all that stuff. For global callbacks of this kind they suggest using .ajaxStart(). .ajaxStart() looks great, except it doesn't expose the XHR so I can add the header.

我应该使用ajaxSetup添加beforeSend吗?有没有办法从ajaxStart访问XHR?其他选项?

Should I just add beforeSend using ajaxSetup? Is there a way to access the XHR from ajaxStart? Other options?

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

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.