Adding custom HTTP headers to Ajax requests enables developers to attach additional information to outbound requests. JavaScript and jQuery provide versatile methods to achieve this customization.
Adding Custom Headers to Individual Requests
To specify HTTP headers for a specific request, utilize the headers property when making the Ajax call:
$.ajax({ url: 'foo/bar', headers: { 'x-my-custom-header': 'some value' } });
Setting Default Headers for All Requests
By employing $.ajaxSetup(), you can establish default headers applicable to all subsequent Ajax requests:
$.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' } });
Adding Headers to Every Request with beforeSend Hook
Another approach to applying headers to all Ajax requests involves the beforeSend hook:
$.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' } });
Note on ajaxSetup:
It's worth mentioning that ajaxSetup only allows for setting a single set of default headers and invoking one beforeSend callback. Multiple ajaxSetup calls will result in only the last defined headers and beforeSend function being applied.
The above is the detailed content of How Can I Add Custom HTTP Headers to Ajax Requests Using JavaScript and jQuery?. For more information, please follow other related articles on the PHP Chinese website!