YUI 3 - Set global request headers for Ajax

I mainly worked with jQuery before, and I'm new to YUI. I want to set a custom header for each Ajax request using IO or DataSource in YUI 3. I want the header to be automatically inserted for each request. In jQuery, I could do this with $ .ajaxPrefilter as follows:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) { var value = 'blah'; if (value) { jqXHR.setRequestHeader("My-Custom-Header", value); } }); 

I found these pages in the online documentation for YUI 3, but I just didn't β€œunderstand”. How can i do this?

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

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

+4
source share
3 answers

Pay attention to the header method in the io module: API documents

I have not tested it, but you should 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 only applies to the current instance of YUI. Therefore, if you have another YUI().use(/.../) statement, you will need to set the header again.

If you need to provide headers through instances, you must define your own module that wraps the functionality of Y.io. Check this meaning to understand what it means.

+4
source

I honestly don't think it is a good idea to do this in a "jQuery style". In any case, you need to provide a configuration object, so a little more characters don't matter much.

But the worst part is that when someone else sees your code, he will have no idea where the additional headers will come from, and he will probably spend hours of his life.

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

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

That way, you explicitly say that you are using an object as a template for the configuration object, and an additional header definition can be found there.

+3
source

I do not know the YUI syntax very well, but try the following:

 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); }); 
+1
source

All Articles