How can I add a custom HTTP header to ajax request with js or jQuery?

前端 未结 9 1114
独厮守ぢ
独厮守ぢ 2020-11-22 03:17

Does anyone know how to add or create a custom HTTP header using JavaScript or jQuery?

相关标签:
9条回答
  • 2020-11-22 04:06

    "setRequestHeader" method of XMLHttpRequest object should be used

    http://help.dottoro.com/ljhcrlbv.php

    0 讨论(0)
  • 2020-11-22 04:17

    You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

    XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
    var newSend = function(vData) {
        this.setRequestHeader('x-my-custom-header', 'some value');
        this.realSend(vData);
    };
    XMLHttpRequest.prototype.send = newSend;
    
    0 讨论(0)
  • 2020-11-22 04:22

    There are several solutions depending on what you need...

    If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

    // Request with custom header
    $.ajax({
        url: 'foo/bar',
        headers: { 'x-my-custom-header': 'some value' }
    });
    

    If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

    $.ajaxSetup({
        headers: { 'x-my-custom-header': 'some value' }
    });
    
    // Sends your custom header
    $.ajax({ url: 'foo/bar' });
    
    // Overwrites the default header with a new header
    $.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
    

    If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

    $.ajaxSetup({
        beforeSend: function(xhr) {
            xhr.setRequestHeader('x-my-custom-header', 'some value');
        }
    });
    
    // Sends your custom header
    $.ajax({ url: 'foo/bar' });
    
    // Sends both custom headers
    $.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });
    

    Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

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