Custom header on every ajax request

asked 2014-07-10 13:05:42 +0800

juminrubin gravatar image juminrubin

Dear ZK Team,

What would be the best way to include a custom header on each request that will be send by zAu.send()?

Would it be a good idea to override the ajaxSendNow function in au.js?

function ajaxSendNow(reqInf) {
    var setting = zAu.ajaxSettings,
        req = setting.xhr(),
        uri = zjq._useQS(reqInf) ? reqInf.uri + '?' + reqInf.content: null;
    zAu.sentTime = jq.now(); 
    try {
        req.onreadystatechange = onResponseReady;
        req.open("POST", uri ? uri: reqInf.uri, true);
        req.setRequestHeader("Content-Type", setting.contentType);
        req.setRequestHeader("ZK-SID", reqInf.sid);
        req.setRequestHeader("MY_CUSTOM_HEADER", "TEST_VALUE");

Thank you.

Best regards,

delete flag offensive retag edit

1 Answer

Sort by ยป oldest newest most voted

answered 2014-07-10 16:18:28 +0800

cor3000 gravatar image cor3000
5673 2 7
ZK Team

yes you found the central point to hook into. However I would prefer not to override such a heavy method, even if it is possible.

Another way would be to override the zAu.ajaxSettings.xhr() function to create a custom XMLHttpRequest object, that will set the header automatically after calling the original open() function.

this example on ZK Fiddle shows how this can be done at page level.

it adds this script to a zul page:

        zk.afterMount(function() {
            var $xhr = zAu.ajaxSettings.xhr;
            zAu.ajaxSettings.xhr = function() {
                var req = $xhr.apply(this, arguments);
                var $open = req.open;
                req.open = function() {
                    $open.apply(req, arguments);
                    req.setRequestHeader('myheader', 'myvalue');
                    console.log("set custom header");
                return req;



link publish delete flag offensive edit


Thank you Robert. Your example teaches me how to extends the AJAX send.

juminrubin ( 2014-07-11 08:26:49 +0800 )edit
Your answer
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools




Asked: 2014-07-10 13:05:42 +0800

Seen: 22 times

Last updated: Jul 10 '14

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More