向所有 jQuery AJAX 请求添加自定义 http 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20356374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add custom http header to all jQuery AJAX Requests
提问by Peter
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 调用没有任何问题,我希望将我的自定义标头自动添加到所有 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 自定义 http 标头问题(不是我的问题),您将看到一个很好的示例,说明如果为每个 ajax 调用手动实现代码是如何工作的。
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.
我想为所有 jQuery ajax 调用覆盖 beforeSend。根据 jQuery 文档,我可以使用jQuery.ajaxSetup()来做到这一点,但有一条警告说你可能不应该这样做,可能会导致意外行为,所有这些。对于这种全局回调,他们建议使用 .ajaxStart()。 .ajaxStart()看起来不错,只是它不公开 XHR,因此我可以添加标题。
Should I just add beforeSend using ajaxSetup? Is there a way to access the XHR from ajaxStart? Other options?
我应该使用 ajaxSetup 添加 beforeSend 吗?有没有办法从 ajaxStart 访问 XHR?其他选择?
回答by Kevin B
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');
}
}
});
this way all requests will get the custom header, unless the specific request overrides the beforeSend option.
这样所有请求都将获得自定义标头,除非特定请求覆盖 beforeSend 选项。
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.
但是请注意,您可以使用 ajaxSetup 实现相同的目标。出现警告的唯一原因是因为使用它会影响所有 ajax 请求(就像我的方法一样),如果特定请求不需要该选项集,可能会导致不需要的结果。我建议只使用ajaxSetup,毕竟这就是它的用途。
回答by Arun P Johny
You can use the ajax global event ajaxSend()
您可以使用 ajax 全局事件ajaxSend()
$( document ).ajaxSend(function( event, jqxhr, settings ) {
jqxhr.setRequestHeader(name, value)
});
Demo: Fiddle
演示:小提琴