【问题标题】:Custom headers on any ajax request using MooTools使用 MooTools 对任何 ajax 请求的自定义标头
【发布时间】:2015-08-11 14:35:07
【问题描述】:

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

根据 jQuery 的 ajaxSetup。

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

谢谢。

【问题讨论】:

  • 它的每个请求而不是为任何请求设置...我需要设置默认标头

标签: ajax xmlhttprequest mootools


【解决方案1】:

您可以继承 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 的其他子类,如Request.HTML 和Request.JSON,它们不会继承更改。

【讨论】:

    猜你喜欢
    • 2016-03-27
    • 1970-01-01
    • 2014-03-10
    • 2023-03-21
    • 2016-06-24
    • 1970-01-01
    • 2010-11-13
    • 2011-12-02
    相关资源
    最近更新 更多