开发者

YUI 3 - Set global request headers for Ajax

开发者 https://www.devze.com 2023-03-18 11:39 出处:网络
I\'ve mostly worked with jQuery before and I\'m new to YUI. I wish to set a custom header for each Ajax request using either IO or DataSource in YUI 3. I want the header to be inserted automatically f

I've mostly worked with jQuery before and I'm new to YUI. I wish to set a custom header for each Ajax request using either IO or DataSource in YUI 3. I want the header to be inserted automatically for each request. In jQuery I could accomplish this with $.ajaxPrefilter like so:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    var value = 'blah';
    if (value) {
        jqXHR.setRequestHeader("My-Custom-He开发者_开发知识库ader", value);
    }
});

I found these pages in the online documentation for YUI 3 but I just don't "get it". How can I accomplish this?

http://developer.yahoo.com/yui/3/examples/io/io-get.html

http://developer.yahoo.com/yui/3/api/io.html


Check out the "header" method in the io module: API docs

I haven't tested it, but you should be able to do something like this:

YUI().use('io', function(Y) {
    Y.io.header('X-My-Header', 'My Custom Value');

    Y.io(/*...*/); // Should have the X-My-Header HTTP header
});

Note that this will only apply to the current YUI instance. So if you have another YUI().use(/.../) statement, you'll need to set the header again.

If you need it to provide headers across instances, you should define your own module that wraps the Y.io functionality. Check out this gist to get a sense of what that entails.


I honestly don't think it is good idea to do it "JQuery style". Either way you need to provide configuration object, so few more characters doesn't make much difference.

But the worst part is that when someone else will see your code he will not have idea where the additional headers come from and he will probably waste hours of his life.

If you still want to have default headers somewhere, do it Javascript way like so:

Y.myDefaultIOCfg={"My-Custom-Header":value}
...
var cfg=Y.merge(Y.myDefaultIOCfg, {
    method: 'GET',
    data: 'foo=bar'
})
request = Y.io(uri, cfg)

This way you explicitly say that you are using some object as a pattern for the config object and additional header definition can be found there.


I don't know YUI syntax very well, but try this:

YUI().use("io-base", function(Y) {
  var cfg, request;

  cfg = {
    methos: 'GET',
    data: 'foo=bar',
    headers: {
      'My-Custom-Header': value
    }
  }

  request = Y.io(uri, cfg);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号