javascript 删除 jQuery.ajaxSetup 中设置的特定请求标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23383891/
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
Remove specific request headers set in jQuery.ajaxSetup
提问by Salman
I setup some custom headers using
我设置了一些自定义标题使用
$.ajaxSetup({
headers : {
'x-custom' : 'value'
}
});
It will addx-custom
header for all the ajax request. But I want some specific requests to NOT contain this header.
它将x-custom
为所有 ajax 请求添加标头。但我希望某些特定请求不包含此标头。
I tried this, delete header from ajaxSettings before that ajax call and add it back when its completed
我试过了,在 ajax 调用之前从 ajaxSettings 中删除标头,并在完成后将其添加回来
delete $.ajaxSettings.headers["x-custom"];
$.ajax({
...
"success": function (data) {
$.ajaxSettings.headers["x-custom"] = 'value';
...
}
});
But I feel this is not the correct way, as the request that fired before finishing that call will not get that header. What else can I do please suggest.
但我觉得这不是正确的方法,因为在完成该调用之前触发的请求不会获得该标头。我还能做什么,请建议。
Should I add the header back in the next line after $.ajax
instead doing it in callback?
我应该在下一行添加标题,$.ajax
而不是在回调中添加标题吗?
回答by Salman
Since this question doesn't have any answer that can be marked as Accepted. I am posting the solution.
由于此问题没有任何可以标记为已接受的答案。我正在发布解决方案。
Looks like adding back the header immediately after the AJAX call would make sense. This way we won't be waiting for success callback and then adding it.
看起来在 AJAX 调用之后立即添加回标头是有意义的。这样我们就不会等待成功回调然后添加它。
delete $.ajaxSettings.headers["x-custom"]; // Remove header before call
$.ajax({
...
"success": function (data) {
...
}
});
$.ajaxSettings.headers["x-custom"] = 'value'; // Add it back immediately
回答by George Siggouroglou
You could add an ajaxComplete function. It will run after all your ajax requests and do whatever you wish.
Something like this,
您可以添加一个 ajaxComplete 函数。它将在您所有的 ajax 请求之后运行并做您想做的任何事情。
像这样的东西,
$(document).ajaxComplete(function(event, xhr, settings) {
// Add the headers again.
$.ajaxSetup({
headers : {
"x-custom" : "value"
}
});
}
});
You can find the documentation here.
Also, as of jQuery 1.8, the .ajaxComplete() method should only be attached to document.
您可以在此处找到文档。
此外,从 jQuery 1.8 开始, .ajaxComplete() 方法应该只附加到 document。