我使用设置了一些自定义标题

$.ajaxSetup({
    headers : {
        'x-custom' : 'value'
    }
});

它将为所有ajax请求添加x-custom header 。但我希望某些特定的请求不包含此 header 。

我试过了,在该ajax调用之前从ajaxSettings删除 header ,并在完成后将其重新添加
delete $.ajaxSettings.headers["x-custom"];

$.ajax({
    ...
    "success": function (data) {
        $.ajaxSettings.headers["x-custom"] = 'value';
        ...
    }
});

但是我觉得这不是正确的方法,因为在完成该调用之前触发的请求将无法获取该 header 。我还能做什么呢?

我应该在$.ajax之后的下一行中重新添加 header ,而不是在回调中添加 header 吗?

最佳答案

由于此问题没有任何答案可以标记为“已接受”。我正在发布解决方案。

看起来在AJAX调用之后立即重新添加 header 会很有意义。这样,我们就不会等待成功回调然后添加它。

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

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

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

09-30 12:57
查看更多