使用 MooTools 对任何 ajax 请求自定义 headers

Custom headers on any ajax request using MooTools

我想知道是否有机会通过设置代码将自定义 headers 添加到我的任何基于 mootools 的 Web 应用程序 ajax 请求中,运行 紧接在 mootools js 之后?

根据 ajaxjQuery 的设置。

注意:我对 Class 扩展不感兴趣。

谢谢。

您可以将 Request 子类化并使用它们自己的 headers 定义您自己的 options,或者您可以只更改原型。

(function(){
    // sets defaults for all request instances
    this['X-Requested-With'] = 'Power';
}.call(Request.prototype.options.headers));

new Request({
    url: '/echo/html/',
    data: {
        html: 'hi'
    },
    method: 'post'
}).send();

等等等等

所以基本上:

var myOptions = {
    'X-Requested-With': 'foo'
};

Object.merge(Request.prototype.options.headers, myoptions);

和扩展:

Request.Fixed = new Class({

    Extends: Request,

    options: {
        headers:  {
            'X-Requested-With': 'foo'
        }
    }
});

new Request.Fixed({
    url: '/echo/html/',
    data: {
        html: 'hi'
    },
    method: 'post'
}).send();

除非您正在解决一个非常特殊的 CORS 问题,否则我会推荐扩展 - 至少它告诉阅读代码的人它没有使用标准的 Request 实例,更容易理解和维护。

I understand you're not interested in subclassing - however, it is the right thing to do, I have had such single line hacks come back and bite me in the backside when domains have changed / configs /code reused and people forgotten the tweak. makes for one hell of a journey to find the reason why it's all broken. Downside of subclassing is other subclasses that extend Request directly like Request.HTML and Request.JSON, they won't inherit the change.