How to modify the ajax header value using jquery

Every time when an AJAX request is initiated, The browser automatically set a bunch of headers values as Accept, Host, User-Agent ,which will be sended to the server.

Sometimes,we may want to set our custom header or change these values such as Authorization, Content-Type.What should we do?
With jQuery ,we can easily to set the custom ajax headers,just use the headers property and beforeSend callback function.

Use headers to set custom ajax headers

$.ajax({
    headers: {
        'Authorization': 'Basic ' + btoa('username:password'),
        'Order-Num': 123
    },
    url: myUrl
});

Use beforeSend callback function to change ajax headers valus.

$.ajax({
    beforeSend: function (jqXHR, settings) {
        jqXHR.setRequestHeader('Authorization', 'Basic ' + btoa('username:password'));
    },
    url: myUrl
});
date2019-04-15 16:39:14 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *