Add custom http header to all jQuery AJAX Requests

前端 未结 2 781
时光说笑
时光说笑 2021-01-01 14:06

Point of clarification: I don\'t have any problem adding a custom header to my jQuery ajax call, I want to have my custom header added to all ajax calls automatically.

相关标签:
2条回答
  • 2021-01-01 14:22

    You can use the ajax global event ajaxSend()

    $( document ).ajaxSend(function( event, jqxhr, settings ) {
        jqxhr.setRequestHeader(name, value)
    });
    

    Demo: Fiddle

    0 讨论(0)
  • 2021-01-01 14:41

    A pre-filter would be an easy way of accomplishing this:

    $.ajaxPrefilter(function( options ) {
        if ( !options.beforeSend) {
            options.beforeSend = function (xhr) { 
                xhr.setRequestHeader('CUSTOM-HEADER-KEY', 'CUSTOM-HEADER-VALUE');
            }
        }
    });
    

    this way all requests will get the custom header, unless the specific request overrides the beforeSend option.

    Note however you can accomplish the same goal using ajaxSetup. the only reason that warning is there is because using it will affect all ajax requests (just like my method will), possibly resulting in unwanted results if a specific request didn't need that option set. I'd suggest just using ajaxSetup, that is what it's there for after all.

    0 讨论(0)
提交回复
热议问题