向所有 jQuery AJAX 请求添加自定义 http 标头 [英] Add custom http header to all jQuery AJAX Requests

查看:29
本文介绍了向所有 jQuery AJAX 请求添加自定义 http 标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

澄清点:向我的 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.

我想为所有 jQuery ajax 调用覆盖 beforeSend.根据 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.

这篇关于向所有 jQuery AJAX 请求添加自定义 http 标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆