Remove specific request headers set in jQuery.ajaxSetup

旧时模样 提交于 2019-12-12 10:29:28

问题


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.

I tried this, delete header from ajaxSettings before that ajax call and add it back when its completed

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?


回答1:


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.

delete $.ajaxSettings.headers["x-custom"]; // Remove header before call

$.ajax({
    ...
    "success": function (data) {
        ...
    }
});

$.ajaxSettings.headers["x-custom"] = 'value'; // Add it back immediately



回答2:


You could add an ajaxComplete function. It will run after all your ajax requests and do whatever you wish.
Something like this,

$(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.



来源:https://stackoverflow.com/questions/23383891/remove-specific-request-headers-set-in-jquery-ajaxsetup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!