問題描述
澄清點:向我的 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 標頭的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!