問題描述
澄清點(diǎn):向我的 jQuery ajax 調(diào)用添加自定義標(biāo)頭沒有任何問題,我希望將我的自定義標(biāo)頭自動(dòng)添加到所有 ajax 調(diào)用.
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 標(biāo)頭問題(不是我的問題),如果為每個(gè) ajax 調(diào)用手動(dòng)實(shí)現(xiàn)代碼,您將看到一個(gè)很好的示例.
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 調(diào)用覆蓋 beforeSend.根據(jù) jQuery 文檔,我可以使用 jQuery.ajaxSetup() 來做到這一點(diǎn),但是有一個(gè)警告說你可能不應(yīng)該,可能會(huì)導(dǎo)致意外行為,所有這些東西.對于這種全局回調(diào),他們建議使用 .ajaxStart()..ajaxStart() 看起來不錯(cuò),只是它沒有公開 XHR,所以我可以添加標(biāo)題.
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.
我應(yīng)該只使用 ajaxSetup 添加 beforeSend 嗎?有沒有辦法從 ajaxStart 訪問 XHR?其他選擇?
Should I just add beforeSend using ajaxSetup? Is there a way to access the XHR from ajaxStart? Other options?
推薦答案
預(yù)過濾器是實(shí)現(xiàn)此目的的簡單方法:
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');
}
}
});
這樣所有請求都將獲得自定義標(biāo)頭,除非特定請求覆蓋了 beforeSend 選項(xiàng).
this way all requests will get the custom header, unless the specific request overrides the beforeSend option.
但是請注意,您可以使用 ajaxSetup 實(shí)現(xiàn)相同的目標(biāo).存在警告的唯一原因是因?yàn)槭褂盟鼤?huì)影響所有 ajax 請求(就像我的方法一樣),如果特定請求不需要該選項(xiàng)集,可能會(huì)導(dǎo)致不需要的結(jié)果.我建議只使用 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.
這篇關(guān)于向所有 jQuery AJAX 請求添加自定義 http 標(biāo)頭的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!